题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
回溯法,利用一个同矩阵大小的bool数组去保存是否遍历过该元素。
class Solution
{
public:
string curStr;
bool hasPath(
char *matrix,
int rows,
int cols,
char *
str)
{
if (matrix == NULL || str == NULL || rows <=
0 || cols <=
0)
return false;
bool *flags =
new bool[strlen(matrix)]();
for (
int i =
0; i < rows; i++
)
for (
int j =
0; j < cols; j++
)
if (helper(matrix, rows, cols, i, j,
0, str, flags))
return true;
return false;
}
bool helper(
char *matrix,
int rows,
int cols,
int i,
int j,
int curLen,
char *str,
bool *
flags)
{
int index = i * cols +
j;
if (i <
0 || i >= rows || j <
0 || j >= cols || matrix[index] != str[curLen] || flags[index] ==
true)
return false;
cout << index <<
endl;
if (curLen == strlen(str) -
1)
return true;
flags[index] =
true;
if (helper(matrix, rows, cols, i -
1, j, curLen +
1, str, flags) || helper(matrix, rows, cols, i +
1, j, curLen +
1, str, flags) || helper(matrix, rows, cols, i, j -
1, curLen +
1, str, flags) || helper(matrix, rows, cols, i, j +
1, curLen +
1, str, flags))
return true;
flags[index] =
false;
return false;
}
};
转载于:https://www.cnblogs.com/ruoh3kou/p/10265508.html