本文共 1093 字,大约阅读时间需要 3 分钟。
需要注意的地方,字符串结尾作为dfs跳出会有bug,当字符串长度等于矩阵所有元素时。
#includeusing namespace std;const int dirX[] = {-1,1,0,0};const int dirY[] = {0,0,-1,1};class Solution {public: bool dfs(bool* flag, const char* m,const int r,const int c, const char* str,int i,int j,int loc){ //printf("<%c %d %d %c>\n",m[i*c+j],i,j,str[loc]); if(str[loc] == 0) return true; if(str[loc] == m[i*c+j] && str[loc+1] == 0) return true; if(str[loc] != m[i*c+j]) return false; flag[i*c+j] = true; bool ans = false; for(int dir=0;dir<4;dir++){ int newi = i + dirX[dir]; int newj = j + dirY[dir]; if(newi >= 0 && newi < r && newj >= 0 && newj < c && flag[newi*c+newj] == false){ ans = ans || dfs(flag,m,r,c,str,newi,newj,loc+1); } } flag[i*c+j] = false; return ans; } bool hasPath(char* matrix, int rows, int cols, char* str) { if(strlen(str) <= 0) return true; bool ans = false; bool flag[rows*cols]; for(int i=0;i
转载地址:http://nfwji.baihongyu.com/