递归回溯,采用深度优先搜索的方法:
class Solution {
public:
bool flag=false;
bool visited[250][250];
bool exist(vector<vector<char>> &board, string word) {
if(word.length()==0) return true;
int m=board.size();
int n=board[0].size();
if(board.size()==0) return true;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
visited[i][i]=false;
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(flag==true) return true;
if(flag==false) DFS(i,j,board,word);
}
}
return flag;
}
void DFS(int x,int y,vector<vector<char>> &board,string word){
if(x<0||y<0||x>=board.size()||y>=board[0].size())
return;
if(word.length()==0){
flag=true;
return;
}
if(flag==true) return;
if(visited[x][y]==true) return;
if(board[x][y]==word.at(0)){
visited[x][y]=true;
if(word.length()==1){//若此处无判定,board只有一个元素的时候,便会出错
flag=true;
return;
}
DFS(x+1,y,board,word.substr(1));
DFS(x,y+1,board,word.substr(1));
DFS(x,y-1,board,word.substr(1));
DFS(x-1,y,board,word.substr(1));
visited[x][y]=false;
}
}
};