|
1 | 1 | class Solution {
|
2 | 2 | public int openLock(String[] deadends, String target) {
|
3 | 3 | 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)) { |
5 | 6 | return -1;
|
6 | 7 | }
|
7 | 8 | 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; |
12 | 13 | int[] rotations = {-1, 1};
|
13 | 14 | while (!queue.isEmpty()) {
|
14 | 15 | int size = queue.size();
|
15 | 16 | for (int i = 0; i < size; i++) {
|
16 | 17 | String removed = queue.remove();
|
17 | 18 | if (removed.equals(target)) {
|
18 |
| - return steps; |
| 19 | + return attempts; |
19 | 20 | }
|
20 | 21 | if (deadEndSet.contains(removed)) {
|
21 | 22 | continue;
|
22 | 23 | }
|
23 | 24 | for (int j = 0; j < 4; j++) {
|
24 | 25 | 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); |
32 | 30 | queue.add(newRotation);
|
33 | 31 | }
|
34 | 32 | }
|
35 | 33 | }
|
36 | 34 | }
|
37 |
| - steps++; |
| 35 | + attempts++; |
38 | 36 | }
|
39 | 37 | return -1;
|
40 | 38 | }
|
|
0 commit comments