-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRobotWalk.java
More file actions
106 lines (88 loc) · 2.69 KB
/
Copy pathRobotWalk.java
File metadata and controls
106 lines (88 loc) · 2.69 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package offer13;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
public class RobotWalk {
// private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
// private int cnt = 0;
// private int m;
// private int n;
// private int k;
//
// public int movingCount(int m, int n, int k) {
//
// this.m = m;
// this.n = n;
// this.k = k;
// int cal;
// boolean[][] flag = new boolean[m][n];
// dfs(0,0,flag);
// return cnt;
// }
// private void dfs(int i, int j,boolean[][] flag ) {
//
// if (i < 0 || i >= m || j< 0 || j >= n || flag[i][j]) {
// return;
// }
// if(cal(i) + cal(j) > k) {
// return;
// }
// cnt++;
// flag[i][j] = true;
// for(int p = 0; p < 4; p++) {
// int newi= i + next[p][0];
// int newj= j + next[p][1];
// dfs(newi , newj , flag);
// }
// }
//
//
// private int cal(int num) {
// int ref = 0;
// while(num > 0) {
// ref += num % 10;
// num /= 10;
// }
// return ref;
// }
public static class Loc {
private int m;
private int n;
public Loc(int m, int n) {
this.m = m;
this.n = n;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
Loc loc = (Loc) obj;
if (loc.m == this.m && loc.n == this.n) return true;
return false;
}
@Override
public int hashCode() {
return Objects.hash(m, n);
}
}
Map<Loc, Boolean> holder = new HashMap<>();
public int count = -1;
public int movingCount(int m, int n, int k){
// holder.put(new Loc(0,0), true);
walk(m, n, 0, 0, k, holder);
return count;
}
public void walk(int m , int n, int cur_m, int cur_n, int k, Map<Loc, Boolean> holder){
//这个位置不可访问
if(cur_m < 0 || cur_m >= m || cur_n < 0 || cur_n >= n) return ;
if(cur_m/10 + cur_m%10 + cur_n/10 + cur_n%10 > k) return;
if(holder.containsKey(new Loc(cur_m, cur_n))) return;
holder.put(new Loc(cur_m, cur_n), true);//此位置可访问,访问当前位置
if(count < holder.size()) count = holder.size();
walk(m, n, cur_m-1, cur_n, k, holder);//上
walk(m, n, cur_m+1, cur_n, k, holder);//下
walk(m, n, cur_m, cur_n-1, k, holder); //左
walk(m, n, cur_m, cur_n+1, k, holder);//右
// holder.remove(new Loc(cur_m, cur_n));//后退时将访问过的位置清空
}
}