题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
题解:
使用回溯法,进行深度遍历,并设置一个visit来标记时候遍历过
1 class Solution {
2 public:
3 bool hasPath(char* matrix, int rows, int cols, char* str)
4 {
5 if (matrix == nullptr || rows < 1 || cols < 1)return false;
6 if (str == nullptr)return true;
7 vector<bool>visit(rows*cols, false);
8 int pot = 0;
9 for (int i = 0; i < rows; ++i)
10 for (int j = 0; j < cols; ++j)
11 if (DFS(matrix, rows, cols, i, j, visit, str, pot))
12 return true;
13 return false;
14 }
15 bool DFS(const char* matrix, const int rows, const int cols,int i, int j, vector<bool>&visit,const char *str, int &pot)
16 {
17 if (str[pot] == '\0')return true;
18 bool flag = false;
19 if (i >= 0 && i < rows && j >= 0 && j < cols &&
20 matrix[i*cols + j] == str[pot] && visit[i*cols + j] == false)
21 {
22 ++pot;
23 visit[i*cols + j] = true;
24 flag = DFS(matrix, rows, cols, i + 1, j, visit, str, pot) ||
25 DFS(matrix, rows, cols, i - 1, j, visit, str, pot) ||
26 DFS(matrix, rows, cols, i, j + 1, visit, str, pot) ||
27 DFS(matrix, rows, cols, i, j - 1, visit, str, pot);
28 if (flag == false)
29 {
30 --pot;
31 visit[i*cols + j] = false;//回溯
32 }
33 }
34 return flag;
35 }
36 };
知识兔