class Solution {
public:
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool st[5][5];
bool dfs(vector<vector<char>>& matrix,int i,int j,int u,string &str)
{
if(u==str.size())
return true;
for (int k = 0; k < 4; k ++ )
{
int x=dx[k]+i,y=dy[k]+j;
if(x<0||x>=matrix.size()||y<0||y>=matrix[x].size())
continue;
if(st[x][y]||matrix[x][y]!=str[u]) continue;
if(dfs(matrix,x,y,u+1,str)) return true;
}
return false;
}
bool hasPath(vector<vector<char>>& matrix, string &str) {
if(!matrix.size()||!matrix[0].size()) return false;
for (int i = 0; i < matrix.size(); i ++ )
for (int j = 0; j < matrix[i].size(); j ++ )
if(str[0]==matrix[i][j]&&!st[i][j])
{
st[i][j]=true;
if(dfs(matrix,i,j,1,str))
return true;
st[i][j]=false;
}
return false;
}
};
标签:return,matrix,23,int,路径,矩阵,st,str,size
From: https://www.cnblogs.com/tangxibomb/p/17228112.html