Skip to content

Commit 17eb20b

Browse files
Create 752-Open-the-lock.java
1 parent c3c0628 commit 17eb20b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

java/752-Open-the-lock.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//Simple BFS solution
2+
3+
class Solution {
4+
public int openLock(String[] deadends, String target) {
5+
String start = "0000";
6+
int ans = 0;
7+
Queue<String> q = new LinkedList<>();
8+
HashSet<String> visited = new HashSet<>();
9+
//Add all the deadends in the visited set so we can ignore them and visited values altogether.
10+
for (String s: deadends)
11+
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);
41+
}
42+
}
43+
}
44+
ans++;
45+
}
46+
return -1;
47+
}
48+
}

0 commit comments

Comments
 (0)