-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInterview13.java
More file actions
59 lines (53 loc) · 1.4 KB
/
Interview13.java
File metadata and controls
59 lines (53 loc) · 1.4 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
package JZOffer2;
import java.util.LinkedList;
import java.util.Queue;
/**
* 深度优先遍历
*/
public class Interview13 {
int m, n, k;
boolean[][] visited;
public int movingCount(int m, int n, int k) {
this.m = m;
this.n = n;
this.k = k;
this.visited = new boolean[m][n];
return dfs(0, 0);
}
private int dfs(int i, int j) {
if(i >= m || j >= n || visited[i][j] || sumPosition(i) + sumPosition(j) > k) {
return 0;
}
visited[i][j] = true;
return 1 + dfs(i + 1, j) + dfs(i, j + 1);
}
private int sumPosition(int x){
return (x % 10) + x / 10;
}
}
/**
* 广度优先遍历
*/
class Interview13_1 {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
int res = 0;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0});
while (queue.size() > 0) {
int[] x = queue.poll();
int i = x[0], j = x[1];
if(i >= m || j >= n || visited[i][j] || sumPosition(i) + sumPosition(j) > k) {
continue;
}
visited[i][j] = true;
res ++;
queue.add(new int[]{i + 1, j});
queue.add(new int[]{i, j + 1});
}
return res;
}
private int sumPosition(int x){
return (x % 10) + x / 10;
}
}