Please design a function to determine whether there is a path containing all characters of a string in a matrix.
The path can start from any cell in the matrix, and each step can move one cell left, right, up, and down in the matrix.
If a path passes through a grid in the matrix, it cannot enter that grid again.
Notice:
输入的路径不为空;
所有出现的字符均为大写英文字母;
Sample
matrix=
[
[“A”,“B”,“C”,“E”],
[“S”,“F”,“C”,“S”],
[“A”,“D”,“E”,“E”]
]
str=“BCCE” , return “true”
str=“ASAE” , return “false”
Problem-solving ideas: brute force search, enumerate all situations
First enumerate all starting points
class Solution {
private boolean dfs(char[][] matrix, String str, int u, int x, int y) {
// System.out.printf("u: %d x: %d y: %d\n", u, x, y);
// if ( matrix[x][y] == str.charAt(u))
// System.out.printf("matrix[x, y]: %c str[u]: %c\n", matrix[0][0], str.charAt(0));
if (matrix[x][y] != str.charAt(u)) return false;
if (u == str.length() - 1) return true;
// if ( matrix[x][y] == str.charAt(u))
// System.out.printf("matrix[x, y]: %c str[u]: %c\n", matrix[0][0], str.charAt(0));
int[] dx = {
-1, 0, 1, 0}, dy = {
0, 1, 0, -1};
char t = matrix[x][y];
matrix[x][y] = '*';
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < matrix.length && b >= 0 && b < matrix[a].length ) {
if (dfs(matrix, str, u + 1, a, b)) return true;
}
}
// 恢复现场
matrix[x][y] = t;
return false;
}
public boolean hasPath(char[][] matrix, String str) {
if (matrix.length == 0) return false;
// 遍历所有的起点
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (dfs(matrix, str, 0, i, j))
return true;
}
}
return false;
}
}