(1)回溯
(2)返回时重置为未访问
class Solution {
private:
vector<vector<char>> d={{1,0},{-1,0},{0,1},{0,-1}};
int ms,ns;
public:
bool helper(vector<vector<char>>& board,vector<vector<bool>> &vis,int i,int j,int len,string &word,int count) {
count++;
if(count==len) {
return true;
}
vis[i][j]=true;
for(int k=0;k<d.size();k++) {
int x1=i+d[k][0];
int y1=j+d[k][1];
if(0<=x1 && x1<ms && 0<=y1 && y1<ns && vis[x1][y1]==false && board[x1][y1]==word[count]) {
if(helper(board,vis,x1,y1,len,word,count)) return true;
}
}
vis[i][j]=false;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
ms=board.size(),ns=board[0].size();
int len=word.length();
vector<vector<bool>> vis(ms,vector<bool>(ns,false));
for(int i=0;i<ms;i++) {
for(int j=0;j<ns;j++) {
if(board[i][j]==word[0]) {
if(helper(board,vis,i,j,len,word,0)) return true;
}
}
}
return false;
}
};