该题也是BFS(递归+回溯)的经典题目,这道题真是花了我不少时间去debug ,对dfs还是不过熟练,还要继续努力!!!
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
int flag=0,row,col;
vector<vector<int> >visited;
bool hasPath(vector<vector<char> >& matrix, string word) {
// write code here
row=matrix.size();//得到行和列
col=matrix[0].size();
visited = vector<vector<int> >(row, vector<int>(col, 0));//初始化为0
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(matrix[i][j]==word[0])//找到第一个字符后
{
dfs(i,j,0,matrix,word);//开始搜索 注意这里还传了一个0初始化cur,cur作为word的下标
if(flag)
return true;
}
}
}
return false;
}
void dfs(int x,int y,int cur,vector<vector<char> >& matrix, string word)
{
if(flag)//边界
return ;
if(x>=0&&x<row&&y>=0&&y<col&&visited[x][y]==0&&matrix[x][y]==word[cur])
{
if(cur==word.length()-1)//边界
{
flag=1;
return ;
}
visited[x][y]=1;//记录走过
dfs(x+1,y,cur+1,matrix,word);//分别是向上
dfs(x,y+1,cur+1,matrix,word);//向右
dfs(x-1,y,cur+1,matrix,word);//向下
dfs(x,y-1,cur+1,matrix,word);//向左 走
visited[x][y]=0;//回来的时候记得恢复
}
}
};
对DFS不熟悉的一定要自己去调试走一下啊喂~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~