题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3x4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用下划线标出)。但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
a b t g
c f c s
j d e h
根据题意,我们肯定需要去探索每条路径的可达性,所以可以考虑使用回溯法解决。
我们先从字符串的第一个字符开始,在矩阵中寻找和第一个字符串相同的字符位置,当找到时再在它的周围找字符串第二个字符的位置...当在矩阵中定位了路径中前面n个字符的位置之后,在与第n个字符对应的格子的周围都没有找到第n+1个字符,这时候需要在路径上回到第n-1个字符,重新定位第n个字符。这种思路即回溯法的思想。
要判断是否进入过某个格子并且控制后续操作不再进入某个格子,我们还需要定义一个和矩阵相同大小的Boolean类型数组来标识。
总的来说,就是直接遍历矩阵,每种路径可能性依次尝试,有一步尝试不行就回退到上一步,继续尝试下一种可能。
实现代码如下:
/**
*
* @param matrix 矩阵对应的二维数组
* @param str 要判断的字符串
* @return
*/
public boolean hasPath(char[][] matrix, String str) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0 || str == null || str.length() == 0) {
System.out.println("invalid input");
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
char[] chars = str.toCharArray();
boolean[][] isVisited = new boolean[rows][cols];
int pathLength = 0;
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++) {
if (hasPathCore(matrix, rows, cols, row, col, chars, pathLength, isVisited))
return true;
}
}
return false;
}
/**
* 递归方法
* @param matrix 矩阵对应的二维数组
* @param rows 行数
* @param cols 列数
* @param row 当前行
* @param col 当前列
* @param chars 字符串的char数组
* @param pathLength 字符串char数组下标
* @param isVisited 布尔类型标识数组
* @return
*/
public boolean hasPathCore(char[][] matrix, int rows, int cols, int row, int col,
char[] chars, int pathLength, boolean[][] isVisited) {
if (pathLength == chars.length)
return true;
boolean hasPath = false;
if (row >= 0 && row < rows && col >= 0 && col < cols
&& matrix[row][col] == chars[pathLength] && !isVisited[row][col]) {
pathLength++;
isVisited[row][col] = true;
hasPath = hasPathCore(matrix, rows, cols, row - 1, col, chars, pathLength, isVisited)
|| hasPathCore(matrix, rows, cols, row + 1, col, chars, pathLength, isVisited)
|| hasPathCore(matrix, rows, cols, row, col - 1, chars, pathLength, isVisited)
|| hasPathCore(matrix, rows, cols, row, col + 1, chars, pathLength, isVisited);
if (!hasPath) { // 不符合条件,退回上一步
pathLength--;
isVisited[row][col] = false;
}
}
return hasPath;
}