public class E12FindPath {
//与C语言不同,此处用全局静态变量用作递归中比较字符的指针
private static int pathLength = 0;
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
if(matrix == null || str == null || rows < 1 || cols < 1)
return false;
//布尔数组用于标记矩阵元素是否已被访问
boolean[] visited = new boolean[rows * cols];
for (boolean bool : visited)
bool = false;
for (int row = 0; row < rows; row++){
for (int col = 0; col < cols; col++){
//每次都重置指针
pathLength = 0;
if (hasPathCore(matrix, rows, cols, str,
row, col,visited))
return true;
}
}
return false;
}
private static boolean hasPathCore(char[] matrix, int rows, int cols, char[] str,
int row, int col, boolean[] visited){
//递归终止条件
if (str.length == pathLength)
return true;
boolean hasPath = false;
if (row >= 0 && row < rows && col >= 0 && col < cols
&& !visited[row * cols + col] && matrix[row * cols + col] == str[pathLength]){
pathLength++;
visited[row * cols + col] = true;
//易犯错误,采用row++,将会改变row本身的值
hasPath = hasPathCore(matrix, rows, cols, str,
row + 1, col, visited) ||
hasPathCore(matrix, rows, cols, str, row - 1, col, visited) ||
hasPathCore(matrix, rows, cols, str, row, col + 1, visited) ||
hasPathCore(matrix, rows, cols, str, row, col - 1, visited);
//此路径不符合则回溯
if (!hasPath){
pathLength--;
visited[row * cols + col] = false;
}
}
return hasPath;
}
//测试用例
public static void main(String[] args){
char[] matrix = {'a', 'b', 'c', 'd', 'e', 'f'};
char[] str = {'b', 'e', 'd'};
System.out.println(E12FindPath.hasPath(matrix, 2, 3, str));
}
}
矩阵中的路径(Java实现)
最新推荐文章于 2020-08-02 20:59:43 发布