-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLeetCode752.java
More file actions
63 lines (58 loc) · 1.82 KB
/
LeetCode752.java
File metadata and controls
63 lines (58 loc) · 1.82 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
package problems;
import java.util.*;
public class LeetCode752 {
public int openLock(String[] deadends, String target) {
if("0000".equals(target)) {
return 0;
}
Set<String> dead = new HashSet<>();
for (String deadend : deadends) {
dead.add(deadend);
}
if(dead.contains("0000")) {
return -1;
}
int step = 0;
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
Set<String> seen = new HashSet<>();
seen.add("0000");
while (!queue.isEmpty()) {
++step;
int size = queue.size();
for (int i = 0; i < size; i++) {
String status = queue.poll();
for(String nextStatus : getList(status)) {
if (!seen.contains(nextStatus) && !dead.contains(nextStatus)) {
if (nextStatus.equals(target)) {
return step;
}
queue.offer(nextStatus);
seen.add(nextStatus);
}
}
}
}
return -1;
}
private char numPrev(char x) {
return x == '0' ? '9' : (char) (x - 1);
}
private char numSucc(char x) {
return x == '9' ? '0' : (char) (x + 1);
}
// 枚举 status 通过一次旋转得到的数字
private List<String> getList(String status) {
List<String> ret = new ArrayList<>();
char[] array = status.toCharArray();
for (int i = 0; i < 4; i++) {
char num = array[i];
array[i] = numPrev(num);
ret.add(new String(array));
array[i] = numSucc(num);
ret.add(new String(array));
array[i] = num;
}
return ret;
}
}