Skip to content

Commit e1fcc31

Browse files
authored
Update Open The Lock.java
1 parent 3e2b8bf commit e1fcc31

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

Medium/Open The Lock.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,38 @@
11
class Solution {
22
public int openLock(String[] deadends, String target) {
33
Set<String> deadEndSet = new HashSet<>(Arrays.asList(deadends));
4-
if (deadEndSet.contains(target) || deadEndSet.contains("0000")) {
4+
String startingPoint = "0000";
5+
if (deadEndSet.contains(startingPoint)) {
56
return -1;
67
}
78
Queue<String> queue = new LinkedList<>();
8-
Set<String> seen = new HashSet<>();
9-
queue.add("0000");
10-
seen.add("0000");
11-
int steps = 0;
9+
Set<String> visited = new HashSet<>();
10+
queue.add(startingPoint);
11+
visited.add(startingPoint);
12+
int attempts = 0;
1213
int[] rotations = {-1, 1};
1314
while (!queue.isEmpty()) {
1415
int size = queue.size();
1516
for (int i = 0; i < size; i++) {
1617
String removed = queue.remove();
1718
if (removed.equals(target)) {
18-
return steps;
19+
return attempts;
1920
}
2021
if (deadEndSet.contains(removed)) {
2122
continue;
2223
}
2324
for (int j = 0; j < 4; j++) {
2425
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);
26+
int newValue = ((removed.charAt(j) - '0') + rotation + 10) % 10;
27+
String newRotation = removed.substring(0, j) + newValue + removed.substring(j + 1);
28+
if (!visited.contains(newRotation)) {
29+
visited.add(newRotation);
3230
queue.add(newRotation);
3331
}
3432
}
3533
}
3634
}
37-
steps++;
35+
attempts++;
3836
}
3937
return -1;
4038
}

0 commit comments

Comments
 (0)