判断在一个矩阵中是否存在一条路径,该路径包含一个字符串的所有字符
路径可以从矩阵中的任意一格开始,每一步可以向上下左右移动。路径中的格不允许重复.
首先可以遍历矩阵找到第一个字符的位置,之后以第一个字符开始,依次向上下左右定位下一个字符的位置。如果定位失败,就回退到上一位置,继续遍历。 辅助矩阵visited
保存矩阵中的点是否被访问
public static boolean hasPath(char[][] matrix, String s) {
if (matrix == null || matrix.length < 1 || matrix[0].length < 1 || s == null)
return false;
int rows = matrix.length;
int cols = matrix[0].length;
boolean[][] visited = new boolean[rows][cols];
char[] str = s.toCharArray();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (hasPathCore(matrix, 0, i, j, visited, str)) {
return true;
}
}
}
return false;
}
public static boolean hasPathCore(char[][] matrix, int pathLength, int row, int col, boolean[][] visited, char[] str) {
if (str.length == pathLength) { //成功找到路径
return true;
}
int rows = matrix.length;
int cols = matrix[0].length;
if (row < rows && row >= 0 && col < cols && col >= 0 &&
str[pathLength] == matrix[row][col] &&
!visited[row][col])
{
visited[row][col] = true;
if (hasPathCore(matrix, pathLength + 1, row - 1, col, visited, str) ||
hasPathCore(matrix, pathLength + 1, row + 1, col, visited, str) ||
hasPathCore(matrix, pathLength + 1, row, col - 1, visited, str) ||
hasPathCore(matrix, pathLength + 1, row, col + 1, visited, str)
) { //下一个字符定位成功
return true;
}
//定位失败,回退
visited[row][col] = false;
}
return false;
}