第一道做出来的中等题
我太难了,做了30分钟
话不多说,下面献上我花30分钟生命写出来的代码
class Solution {
public:
bool hasPath(vector<vector<char>>& matrix, string &str) {
for(long unsigned int j=0; j < matrix.size();j++){
for(long unsigned int i=0;i < matrix[j].size();i++){
if(dfs(j,i,matrix,str,0))return true;
}
}
return false;
}
bool dfs(long unsigned int x,long unsigned int y,vector<vector<char>>& matrix,string &str,int l){
if(x<0||x>=matrix.size()||y<0||y>=matrix[x].size())return false;
if(matrix[x][y]=='*')return false;
if(matrix[x][y]!=str[l])return false;
if(l==str.size()-1)return true;
char e=matrix[x][y];
matrix[x][y]='*';
bool s;
if(dfs(x+1,y,matrix,str,l+1))return true;
if(dfs(x-1,y,matrix,str,l+1))return true;
if(dfs(x,y+1,matrix,str,l+1))return true;
if(dfs(x,y-1,matrix,str,l+1))return true;
matrix[x][y]=e;
return false;
}
};