-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenLock.java
More file actions
56 lines (38 loc) · 1.31 KB
/
openLock.java
File metadata and controls
56 lines (38 loc) · 1.31 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
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> dead = new HashSet<>(Arrays.asList(deadends));
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
int moves = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String curr = queue.poll();
if (dead.contains(curr)) continue;
if (curr.equals(target)) return moves;
for (String next : getNeighbors(curr)) {
if (!visited.contains(next)) {
visited.add(next);
queue.offer(next);
}
}
}
moves++;
}
return -1;
}
private static List<String> getNeighbors(String s) {
List<String> res = new ArrayList<>();
char[] arr = s.toCharArray();
for (int i = 0; i < 4; i++) {
char ch = arr[i];
arr[i] = (char) ((ch - '0' + 1) % 10 + '0');
res.add(new String(arr));
arr[i] = (char) ((ch - '0' + 9) % 10 + '0');
res.add(new String(arr));
arr[i] = ch;
}
return res;
}
}