-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
45 lines (44 loc) · 1.3 KB
/
Solution.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
class Solution {
public int openLock(String[] deadends, String target) {
if ("0000".equals(target)) {
return 0;
}
Set<String> s = new HashSet<>(Arrays.asList(deadends));
if (s.contains("0000")) {
return -1;
}
Deque<String> q = new ArrayDeque<>();
q.offer("0000");
s.add("0000");
int ans = 0;
while (!q.isEmpty()) {
++ans;
for (int n = q.size(); n > 0; --n) {
String p = q.poll();
for (String t : next(p)) {
if (target.equals(t)) {
return ans;
}
if (!s.contains(t)) {
q.offer(t);
s.add(t);
}
}
}
}
return -1;
}
private List<String> next(String t) {
List res = new ArrayList<>();
char[] chars = t.toCharArray();
for (int i = 0; i < 4; ++i) {
char c = chars[i];
chars[i] = c == '0' ? '9' : (char) (c - 1);
res.add(String.valueOf(chars));
chars[i] = c == '9' ? '0' : (char) (c + 1);
res.add(String.valueOf(chars));
chars[i] = c;
}
return res;
}
}