判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向上下左右移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
public class Solution {
private int[][] next = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
private int rows;
private int cols;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
this.rows = rows;
this.cols = cols;
char[][] matArr = getMatrix(matrix);
boolean[][] markarr = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (backTracking(matArr, 0, i, j, str, markarr)) {
return true;
}
}
}
return false;
}
private boolean backTracking(char[][] matArr, int pathlen, int r, int c, char[] str, boolean[][] markarr) {
if (r < 0 || r >= rows || c < 0 || c >= cols || str[pathlen] != matArr[r][c] || markarr[r][c]) {
return false;
}
if(pathlen == str.length-1)
return true;
markarr[r][c] = true;
for (int[] n : next) {
if (backTracking(matArr, pathlen + 1, r + n[0], c + n[1], str, markarr)) {
return true;
}
}
markarr[r][c] = false;
return false;
}
private char[][] getMatrix(char[] matrix) {
char[][] ret = new char[rows][cols];
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
ret[i][j] = matrix[index++];
}
}
return ret;
}
}
来源:CSDN
作者:mhHao
链接:https://blog.csdn.net/hmh13548571896/article/details/104117565