Skip to content

Commit 41ea135

Browse files
authored
Create Open The Lock.java
1 parent 70c3ae8 commit 41ea135

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Medium/Open The Lock.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public int openLock(String[] deadends, String target) {
3+
Set<String> deadEndSet = new HashSet<>(Arrays.asList(deadends));
4+
if (deadEndSet.contains(target) || deadEndSet.contains("0000")) {
5+
return -1;
6+
}
7+
Queue<String> queue = new LinkedList<>();
8+
Set<String> seen = new HashSet<>();
9+
queue.add("0000");
10+
seen.add("0000");
11+
int steps = 0;
12+
int[] rotations = {-1, 1};
13+
while (!queue.isEmpty()) {
14+
int size = queue.size();
15+
for (int i = 0; i < size; i++) {
16+
String removed = queue.remove();
17+
if (removed.equals(target)) {
18+
return steps;
19+
}
20+
if (deadEndSet.contains(removed)) {
21+
continue;
22+
}
23+
for (int j = 0; j < 4; j++) {
24+
for (int rotation : rotations) {
25+
int changedVal = ((removed.charAt(j) - '0') + rotation + 10) % 10;
26+
String newRotation = new StringBuilder()
27+
.append(removed.substring(0,j)) .append(changedVal)
28+
.append(removed.substring(j + 1))
29+
.toString();
30+
if (!seen.contains(newRotation)) {
31+
seen.add(newRotation);
32+
queue.add(newRotation);
33+
}
34+
}
35+
}
36+
}
37+
steps++;
38+
}
39+
return -1;
40+
}
41+
}

0 commit comments

Comments
 (0)