思路:
- dfs,重点写在注释里面。这道题做了好久,以后不做无意义的尝试,想好了再改,调试。
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size(); j++){
if(dfs(board,0,i,j,word))
return true;
}
}
return false;
}
bool dfs(vector<vector<char>>& board,int cur,int i,int j,string word){
if(i < 0 || j < 0 || i >= board.size() ||j >= board[0].size()) return false; //应该放在开头,否则下面board[i][j]有可能越界
if(cur == word.size()-1 && board[i][j] == word[cur]) return true;
if(board[i][j] == '0') return false;
if(board[i][j] != word[cur]) return false;
if(board[i][j] == word[cur]){
char tmp = board[i][j];
board[i][j] = '0';
if(dfs(board,cur+1,i+1,j,word) || dfs(board,cur+1,i-1,j,word) || dfs(board,cur+1,i,j+1,word) || dfs(board,cur+1,i,j-1,word)) return true; //这里要有返回结果
board[i][j] = tmp;
return false;
}
}
};