-
题:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
-
解题思路:回溯法,使用递归。
要点:
1、定义row、column生成矩阵
2、先默认标记为符合条件,然后遍历4个方向,递归完成路径深度遍历,最后判断条件不满足时,将标记恢复
注意:
通常二维矩阵上查找路径都可以通过回溯法解决
实现:
public class PathInMatrix {
public static void main(String args[]) {
char[] matrix = new char[]{'A', 'B', 'C', 'E', 'S', 'F', 'C', 'S', 'A', 'D', 'E', 'E'};
char[] str = new char[]{'A', 'B', 'C', 'C', 'E', 'D'};
System.out.println(hasPath(matrix, 3, 4, str));
}
public static boolean hasPath(char[] matrix, int rows, int clos, char[] str) {
if (matrix == null || str == null || matrix.length < 1 || matrix.length < str.length) {
return false;
}
boolean[] visited = new boolean[rows * clos];
int curLength = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < clos; j++) {
return coreHasPath(matrix, rows, clos, i, j, str, visited, curLength);
}
}
return false;
}
private static boolean coreHasPath(char[] matrix, int rows, int cols, int row, int col, char[] str, boolean[] visited, int curLength) {
if (curLength == str.length) {
return true;
}
boolean hasPath = false;
if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row * cols + col] && matrix[row * cols + col] == str[curLength]) {
curLength++;
// 先默认标记为符合条件
visited[row * cols + col] = true;
// 遍历4个方向,递归完成路径深度遍历
hasPath = coreHasPath(matrix, rows, cols, row - 1, col, str, visited, curLength) ||
coreHasPath(matrix, rows, cols, row + 1, col, str, visited, curLength) ||
coreHasPath(matrix, rows, cols, row, col - 1, str, visited, curLength) ||
coreHasPath(matrix, rows, cols, row, col + 1, str, visited, curLength);
// 条件不满足时,将标记恢复
if (!hasPath) {
visited[row * cols + col] = false;
}
}
return hasPath;
}
}