思路:递归。用一个visit矩阵记录某个位置是否被访问,然后对board进行遍历,并对每个位置的上下左右分别调用DFS递归函数。
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size()==0||board[0].size()==0) return false;
int m=board.size(),n=board[0].size();
vector<vector<bool> > visit(m,vector<bool>(n,false));
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
if (existDFS(board,word,0,i,j,visit)) return true;
return false;
}
bool existDFS(vector<vector<char> > & board,string word,int level,int i,int j,vector<vector<bool> > &visit)
{
if(level==word.size()) return true;
int m=board.size(),n=board[0].size();
if(i<0||j<0||i>=m||j>=n||board[i][j]!=word[level]||visit[i][j]) return false;
visit[i][j]=true;
bool ans=existDFS(board,word,level+1,i,j-1,visit)||
existDFS(board,word,level+1,i,j+1,visit)||existDFS(board,word,level+1,i-1,j,visit)||existDFS(board,word,level+1,i+1,j,visit);
visit[i][j]=false;
return ans;
}
};