矩阵中的路径
问题描述:判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中任意一格开始,每一步可以在矩阵中间向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
本方法思想:使用回溯法。代码中有num记录共有多少种情况,暂时还存在些许错误,之后会改正,但是是否存在路径的判断是正确的,代码中也有大量注释,能够完成判断路径是否存在,具体见代码。
持续更新...
代码附下
Java实现:
package 矩阵中的路径;
/**
* 判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中任意一格开始 每一步可以在矩阵中间向左、右、上、下移动一格。
* 如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
* @author user
*/
public class Test {
public static int num = 0;// 计数不对,不要用
/**
* *
* @param matrix输入矩阵
* @param rows行数
* @param cols列数
* @param str查询路径
* @return
*/
public static boolean hasPath(char[][] matrix, char[] str) {
// 参数检验
if (matrix == null || str == null) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
// 变量初始化,没有访问过为false 访问过为true
boolean[][] visited = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
visited[i][j] = false;
}
}
// 记录结果,数量
int pathLength = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (hasPathCore(matrix, str, visited, i, j, pathLength)) {
return true;
}
}
}
return false;
}
/**
*
* @param matrix
* @param str
* @param visited
* @param i
* 当前行数
* @param j
* 当前列数
* @param pathLength
* @return
*/
private static boolean hasPathCore(char[][] matrix, char[] str, boolean[][] visited, int i, int j, int pathLength) {
int m = matrix.length;
int n = matrix[0].length;
if (pathLength == str.length) {
num++;
return true;
}
boolean hasPath = false;
if (i >= 0 && i < m && j >= 0 && j < n && matrix[i][j] == str[pathLength] && visited[i][j] == false) {
visited[i][j] = true;
pathLength++;
// 找到以后,递归去找一下个
hasPath = hasPathCore(matrix, str, visited, i, j - 1, pathLength)
| hasPathCore(matrix, str, visited, i - 1, j, pathLength)
| hasPathCore(matrix, str, visited, i, j + 1, pathLength)
| hasPathCore(matrix, str, visited, i + 1, j, pathLength);
if (!hasPath) {
pathLength--;
visited[i][j] = false;
}
}
return hasPath;
}
public static void main(String[] args) {
char[][] matrix = new char[3][4];
char ch1[] = { 'a', 'b', 'c', 'd' };
char ch2[] = { 'b', 'c', 'd', 'a' };
char ch3[] = { 'c', 'd', 'a', 'b' };
matrix[0] = ch1;
matrix[2] = ch3;
matrix[1] = ch2;
char str[] = { 'a', 'b', 'c', 'd' };
boolean b = hasPath(matrix, str);
System.out.println(b);
System.out.println(num);
}
}
持续更新...欢迎赞赏!
https://blog.csdn.net/ustcer_93lk/article/details/80368883
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。