Skip to content

Commit 392f504

Browse files
Update 0752-open-the-lock.java
1 parent b14a651 commit 392f504

File tree

1 file changed

+38
-39
lines changed

1 file changed

+38
-39
lines changed

java/0752-open-the-lock.java

+38-39
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,47 @@
1-
//Simple BFS solution
2-
31
class Solution {
4-
52
public int openLock(String[] deadends, String target) {
6-
String start = "0000";
7-
int ans = 0;
8-
Queue<String> q = new LinkedList<>();
9-
HashSet<String> visited = new HashSet<>();
10-
//Add all the deadends in the visited set so we can ignore them and visited values altogether.
11-
for (String s : deadends) visited.add(s);
12-
q.offer(start);
13-
while (!q.isEmpty()) {
14-
int size = q.size();
15-
for (int j = 0; j < size; j++) {
16-
String str = q.poll();
17-
StringBuilder cur = new StringBuilder(str);
18-
if (str.equals(target)) return ans;
19-
if (!visited.contains(cur.toString())) {
20-
for (int i = 0; i < start.length(); i++) {
21-
//edge case for 0
22-
if (cur.charAt(i) == '0') {
23-
cur.setCharAt(i, '1');
24-
q.offer(cur.toString());
25-
cur.setCharAt(i, '9');
26-
q.offer(cur.toString());
27-
} else if (cur.charAt(i) == '9') { //edge case for 9
28-
cur.setCharAt(i, '0');
29-
q.offer(cur.toString());
30-
cur.setCharAt(i, '8');
31-
q.offer(cur.toString());
32-
} else {
33-
cur.setCharAt(i, ((char) (cur.charAt(i) + 1)));
34-
q.offer(cur.toString());
35-
cur.setCharAt(i, ((char) (cur.charAt(i) - 2)));
36-
q.offer(cur.toString());
37-
}
38-
visited.add(str);
39-
cur.setLength(0);
40-
cur.append(str);
3+
Set<String> visited = new HashSet<>();
4+
for (String deadend : deadends) {
5+
if (deadend.equals("0000")) {
6+
return -1;
7+
}
8+
visited.add(deadend);
9+
}
10+
11+
Queue<String> queue = new LinkedList<>();
12+
queue.offer("0000");
13+
visited.add("0000");
14+
15+
int turns = 0;
16+
while (!queue.isEmpty()) {
17+
int size = queue.size();
18+
for (int i = 0; i < size; i++) {
19+
String lock = queue.poll();
20+
if (lock.equals(target)) {
21+
return turns;
22+
}
23+
List<String> children = generateChildren(lock);
24+
for (String child : children) {
25+
if (!visited.contains(child)) {
26+
visited.add(child);
27+
queue.offer(child);
4128
}
4229
}
4330
}
44-
ans++;
31+
turns++;
4532
}
4633
return -1;
4734
}
35+
36+
private List<String> generateChildren(String lock) {
37+
List<String> children = new ArrayList<>();
38+
for (int i = 0; i < 4; i++) {
39+
char[] digits = lock.toCharArray();
40+
digits[i] = (char)(((digits[i] - '0' + 1) % 10) + '0');
41+
children.add(new String(digits));
42+
digits[i] = (char)(((digits[i] - '0' - 2 + 10) % 10) + '0');
43+
children.add(new String(digits));
44+
}
45+
return children;
46+
}
4847
}

0 commit comments

Comments
 (0)