题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。例如:
a b c e
s f c s
a d e e
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:
1)根据给定数组,初始化一个标志位数组,初始化为false,表示未走过,true表示已经走过,不能走第二次
2)根据行数和列数,遍历数组,先找到一个与str字符串的第一个元素相匹配的矩阵元素,进入isSubPath
3)根据i和j先确定一维数组的位置,因为给定的matrix是一个一维数组
4)确定递归终止条件:越界,当前找到的矩阵值不等于数组对应位置的值,已经走过的,这三类情况,都直接false,说明这条路不通
5)若index=str.length()-1,则待判定的字符串str的索引已经判断到了最后一位,说明匹配成功,返回true
6)回溯重点,递归不断地寻找周围四个格子是否符合条件,只要有一个格子符合条件,就继续再找这个符合条件的格子的四周是否存在符合条件的格子,直到index到达末尾或者不满足递归条件就停止。
7)走到这一步,说明本次是不成功的,我们要还原一下标志位数组index处的标志位,进入下一轮的判断。
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if (matrix == nullptr || str == nullptr || rows < 1 || cols < 1)
return false;
bool* flag = new bool[rows*cols];
memset(flag, false, rows*cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
//循环遍历二维数组matrix,找到起点等于str第一个元素的值,在递归判断四周是否有符合条件的
if (isSubPath(matrix, rows, cols, i, j, 0, str, flag)) {
return true;
}
}
}
delete[] flag;
return false;
}
bool isSubPath(char* matrix, int rows, int cols, int r, int c, int index, char* str, bool* flag) {
if (str[index] == '\0') return true; //递归终止条件
if (r < 0 || r >= rows || c < 0 || c >= cols || matrix[r*cols + c] != str[index] || flag[r*cols + c] == true) return false;
flag[r*cols + c] = true; //要走的第一个位置置为true,表示已经走过了
//回溯,递归寻找下一路径节点,每次找到了就给index+1,找不到则返回上一级再判断
if (isSubPath(matrix, rows, cols, r + 1, c, index + 1, str, flag)
|| isSubPath(matrix, rows, cols, r, c + 1, index + 1, str, flag)
|| isSubPath(matrix, rows, cols, r - 1, c, index + 1, str, flag)
|| isSubPath(matrix, rows, cols, r, c - 1, index + 1, str, flag))
return true;
flag[r*cols + c] = false; //能走到这,说明该条路径不通,往上还原,再尝试其它路径
return false;
}
};
其中,判断是否是子路径isSubPath也可以写成如下:
bool isSubPath(char* matrix, int rows, int cols, int r, int c, int index, char* str, bool* flag) {
if (str[index] == '\0') return true; //递归终止条件
bool subpath=false;
if (r >= 0 && r < rows && c >= 0 && c < cols && flag[r*cols + c] == false && matrix[r*cols + c] == str[index]) {
flag[r*cols + c] = true;
subpath = isSubPath(matrix, rows, cols, r + 1, c,index+1, str, flag)
|| isSubPath(matrix, rows, cols, r, c + 1,index+1, str, flag)
|| isSubPath(matrix, rows, cols, r - 1, c,index+1, str, flag)
|| isSubPath(matrix, rows, cols, r, c - 1,index+1, str, flag);
if(subpath==false){
// index--;
flag[r*cols + c] = false;
}
}
return subpath;
}