-
Notifications
You must be signed in to change notification settings - Fork 17
/
Que65.java
53 lines (37 loc) · 1.28 KB
/
Que65.java
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
44
45
46
47
48
49
50
51
52
53
/**
* @author: hyl
* @date: 2019/08/17
**/
public class Que65 {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
int[] flag = new int[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, int[] flag) {
//计算出在matrix中的位置
int index = i * cols + j;
if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[k] || flag[index] == 1){
return false;
}
if(k == str.length - 1){
return true;
}
flag[index] = 1;
if (helper(matrix , rows , cols , i - 1 , j , str , k + 1, flag)
||helper(matrix , rows , cols , i + 1 , j , str , k + 1, flag)
||helper(matrix , rows , cols , i , j + 1 , str , k + 1, flag)
||helper(matrix , rows , cols , i , j - 1 , str , k + 1, flag)){
return true;
}
flag[index] = 0;
return false;
}
}