Repository navigation
Expand file tree
/
Copy pathpathinmartix.java
More file actions
64 lines (60 loc) · 2.74 KB
/
Copy pathpathinmartix.java
File metadata and controls
64 lines (60 loc) · 2.74 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package swordToOffer;
public class pathinmartix {
public static void main(String[] args){
char[] matrix =new char[]{'a','b','c','e','s','f','c','s','a','d','e','e'};
System.out.println(hashPath(matrix,3,4,new char[]{'a','b','c','c','e','d'})); //'b','c','c','e','d'
}
public static boolean hashPath(char[] matrix, int rows, int cols, char[] str) {
char[][] chars = new char[rows][cols];
int[][] visited = new int[rows][cols];
int index = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
chars[i][j] = matrix[index++];
}
}
boolean result = false;
ko:
for(int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(chars[i][j] == str[0]){
visited[i][j] = 1;
result = util(chars, str, 1, i, j,visited);
visited[i][j] = 0;
}
if(result) break ko;
}
}
return result;
}
/*
*
* */
public static boolean util(char[][] chars, char[] str, int index,int row, int col, int[][] visited) {
boolean result = false;
if(index == str.length ) result = true;
else {
if (row - 1 >= 0 && str[index] == chars[row - 1][col] ) { //向上走
visited[row - 1][col] = 1;
result = util(chars, str, index + 1, row - 1, col, visited);
visited[row - 1][col] = 0;
}
if (row + 1 <= chars.length - 1 && str[index] == chars[row + 1][col] && !result) { // 向下走
visited[row + 1][col] = 1;
result = util(chars, str, index + 1, row + 1, col, visited);
visited[row + 1][col] = 0;
}
if(col - 1 >= 0 && str[index] == chars[row][col - 1] && !result) { // 往左走
visited[row ][col - 1] = 1;
result = util(chars, str, index + 1, row , col - 1, visited);
visited[row ][col - 1] = 0;
}
if(col +1 <= chars[0].length - 1 && str[index] == chars[row][col + 1] && !result) { // 往右走
visited[row ][col+ 1] = 1;
result = util(chars, str, index + 1, row , col + 1, visited);
visited[row ][col+ 1] = 0;
}
}
return result;
}
}