请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 "a b c e s f c s a d e e" 的3 x 4的矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
AC之后看了好多人的代码,感觉很乱,这里分享一个舒适的写法
大概意思就是,从str中找出头头,去矩阵中找,找到后,以那个点为开始,进行dfs。
class Solution {
public:
int dir[4][2]={
0,1,
0,-1,
-1,0,
1,0
};
bool mp[55][55] = {0};
int strLen;
int isOk = false;
int dx, dy;
int nx, ny;
bool hasPath(char* matrix, int rows, int cols, char* str)
{
nx = rows;
ny = cols;
strLen = strlen(str);
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(matrix[i * cols + j] == str[0]){
mp[i][j] = true;
dfs(i, j, 1, matrix, str);
mp[i][j] = false;
}
}
}
return isOk;
}
void dfs(int tx, int ty, int step, char* matrix, char* str){
if(step == strLen){
isOk = true;
return ;
}
for(int i = 0; i < 4; i ++){
dx = tx + dir[i][0];
dy = ty + dir[i][1];
if(dx < 0 || dy < 0 || dx >= nx || dy >= ny) continue;
if(!mp[dx][dy] && matrix[dx * ny + dy] == str[step]){
mp[dx][dy] = true;
dfs(dx, dy, step + 1, matrix, str);
mp[dx][dy] = false;
}
}
}
};