题目:
题1:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
知识点:
- 回溯法:非常适合由多个步骤组成的问题,并且每个步骤都有多个选项;通常回溯法算法适合用递归实现
代码实现:
public static void main(String[] args) {
char[] matrix = "ABTGCFCSJDEH".toCharArray();
int rows = 3;
int cols = 4;
char[] str = "ABFB".toCharArray();
if (hasPath(matrix, rows, cols, str)) {
System.out.println("Yes!");
} else {
System.out.println("No!");
}
}
private static boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if (matrix == null || rows < 1 || cols < 1 || str == null) {
return false;
}
// 定义一个布尔矩阵记录格子是否遍历过
boolean[] isVisit = new boolean[rows * cols];
int pathLenth = 0;
// 遍历矩阵找符合条件的元素
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (hasPathCore(matrix, rows, cols, row, col, str, isVisit, pathLenth)) {
return true;
}
}
}
return false;
}
/**
* 判断是否为要查找路径上的节点
*
* @return
*/
private static boolean hasPathCore(char[] matrix, int rows, int cols, int row, int col, char[] str,
boolean[] isVisit, int pathLenth) {
// 判断1.是否出界 2.是否访问过 3.此字符是否为查找的字符
if (row < 0 || col < 0 || row >= rows || col >= cols || isVisit[row * cols + col] == true
|| matrix[row * cols + col] != str[pathLenth]) {
return false;
}
// 若达到查找路径长度,返回true
if (pathLenth == str.length - 1) {
return true;
}
// 访问到了该元素,对应的isVisit变为true
isVisit[row * cols + col] = true;
// 判断上下左右是否有下一个搜索的元素
if(hasPathCore(matrix, rows, cols, row - 1, col, str, isVisit, pathLenth+1)
|| hasPathCore(matrix, rows, cols, row + 1, col, str, isVisit, pathLenth+1)
|| hasPathCore(matrix, rows, cols, row, col - 1, str, isVisit, pathLenth+1)
|| hasPathCore(matrix, rows, cols, row, col + 1, str, isVisit, pathLenth+1)) {
return true;
}
// 若没有,标记取消,回溯到上一个元素
isVisit[row * cols + col] = false;
return false;
}