-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0752-open-the-lock.java
47 lines (44 loc) · 1.48 KB
/
0752-open-the-lock.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
46
47
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> visited = new HashSet<>();
for (String deadend : deadends) {
if (deadend.equals("0000")) {
return -1;
}
visited.add(deadend);
}
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
visited.add("0000");
int turns = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String lock = queue.poll();
if (lock.equals(target)) {
return turns;
}
List<String> children = generateChildren(lock);
for (String child : children) {
if (!visited.contains(child)) {
visited.add(child);
queue.offer(child);
}
}
}
turns++;
}
return -1;
}
private List<String> generateChildren(String lock) {
List<String> children = new ArrayList<>();
for (int i = 0; i < 4; i++) {
char[] digits = lock.toCharArray();
digits[i] = (char)(((digits[i] - '0' + 1) % 10) + '0');
children.add(new String(digits));
digits[i] = (char)(((digits[i] - '0' - 2 + 10) % 10) + '0');
children.add(new String(digits));
}
return children;
}
}