给出一个字符矩阵和一个字符串路径,返回矩阵中是否存在这一路径
比较典型的用回溯法解决的问题,相似的还有迷宫找出口,扫雷游戏里点击显示连续无数字区域的功能也可以用这个思路做。
代码:
package com.zxy.exercise;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//回溯法练习
//给出字符矩阵和字符串路径,判断矩阵中是否包含该路径
char[][] matrix = {{'a', 'b', 'c', 'e'},
{'s', 'f', 'c', 's'},
{'a', 'd', 'e', 'e'}};
String path = "bcced";
if(hasPath(matrix, path))
System.out.println("True");
else {
System.out.println("False");
}
}
public static boolean hasPath(char[][] matrix, String path){
if(matrix == null || path == "" || path == null)
return false;
int rows = matrix.length;
int cols = matrix[0].length;
Integer pathPos = new Integer(0);
boolean[][] visited = new boolean[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
visited[i][j] = false;
}
}
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(findPath(matrix, i, j, path, pathPos, visited))
return true;
}
}
return false;
}
public static boolean findPath(char[][] matrix, int row, int col, String path, Integer pathPos, boolean[][] visited){
if(pathPos.intValue() == path.length())
return true;
boolean hasPath = false;
if(row < matrix.length && row >= 0 && col < matrix[0].length && col >= 0 && matrix[row][col] == path.charAt(pathPos) && !visited[row][col]){
pathPos++;
visited[row][col] = true;
hasPath = findPath(matrix, row + 1, col, path, pathPos, visited)
|| findPath(matrix, row, col + 1, path, pathPos, visited)
|| findPath(matrix, row - 1, col, path, pathPos, visited)
|| findPath(matrix, row, col - 1, path, pathPos, visited);
if(!hasPath){
pathPos--;
visited[row][col] = false;
}
}
return hasPath;
}
}
这道题是给出了路径求是否存在,迷宫是确定存在求路径,思路一样,只是如果求路径的话一般用栈来保存。