-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixPath.java
More file actions
43 lines (41 loc) · 1.19 KB
/
MatrixPath.java
File metadata and controls
43 lines (41 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package matrixPath;
public class MatrixPath {
/**
* @param matrix
* 矩阵字符串
* @param rows
* 矩阵行
* @param cols
* 矩阵列
* @param str
* 字符串路径
* @return 存在一条路径返回true,否则false
*/
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
boolean flag[] = new boolean[matrix.length];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (helper(matrix, rows, cols, i, j, str, 0, flag))
return true;
}
}
return false;
}
private boolean helper(char[] matrix, int rows, int cols, int i, int j, char[] str, int k, boolean[] flag) {
int index = i * cols + j;
if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[k] || flag[index])
return false;
if (k == str.length - 1)
return true;
flag[index] = true;
if ( helper(matrix, rows, cols, i - 1, j, str, k + 1, flag) // up
|| helper(matrix, rows, cols, i + 1, j, str, k + 1, flag) // down
|| helper(matrix, rows, cols, i, j - 1, str, k + 1, flag) // left
|| helper(matrix, rows, cols, i, j + 1, str, k + 1, flag) // right
) {
return true;
}
flag[index] = false;
return false;
}
}