请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:
利用回溯法,新建一个boolean[] visited数组,用来表示已经访问过的结点。然后依次递归上下左右四个结点,否则,返回false。当index == str.length的时候,就说明匹配成功了。如果有一条路能通,那么就返回true。
public class Solution {
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
boolean[] visited = new boolean[matrix.length];
int[] index = new int[]{0};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (find(matrix, rows, cols, str, i, j, index, visited)) {
return true;
}
}
}
return false;
}
// i代表行数, j代表列数
public static boolean find(char[] matrix, int rows, int cols, char[] str, int i, int j, int[] index, boolean[] visited) {
if (index[0] == str.length) {
return true;
}
boolean flag = false;
if (i >= 0 && j >= 0 && i < rows && j < cols && matrix[i * cols + j] == str[index[0]] && !visited[i * cols + j]) {
visited[i * cols + j] = true;
index[0]++;
flag = find(matrix, rows, cols, str, i, j + 1, index, visited)
|| find(matrix, rows, cols, str, i, j - 1, index, visited)
|| find(matrix, rows, cols, str, i - 1, j, index, visited)
|| find(matrix, rows, cols, str, i + 1, j, index, visited);
if (!flag) {
index[0]--;
visited[i * cols + j] = false;
}
}
return flag;
}
}


被折叠的 条评论
为什么被折叠?



