需要注意的地方,字符串结尾作为dfs跳出会有bug,当字符串长度等于矩阵所有元素时。
#include <bits/stdc++.h>
using 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<rows;i++){
for(int j=0;j<cols;j++){
if(matrix[i*cols+j] == str[0]){
memset(flag,0,sizeof(flag));
ans = ans || dfs(flag,matrix,rows,cols,str,i,j,0);
}
}
}
return ans;
}
};
int main(){
Solution S;
char a[] = "AAAAAAAAAAAA";
char b[] = "AAAAAAAAAAAA";
printf("%s\n",S.hasPath(a,3,4,b)?"YES":"NO");
return 0;
}
本文介绍了一个使用深度优先搜索(DFS)算法解决的问题:判断给定的字符矩阵中是否存在一条路径,使得路径上的字符顺序组成给定的目标字符串。文章提供了一个C++实现示例,并讨论了在实现过程中需要注意的一些细节。
1233

被折叠的 条评论
为什么被折叠?



