-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathOpenTheLock.java
More file actions
79 lines (65 loc) · 2.19 KB
/
OpenTheLock.java
File metadata and controls
79 lines (65 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* LeetCode 752 https://leetcode.com/problems/open-the-lock/
*/
class Solution {
private String plusOne(String str, int index) {
char[] ch = str.toCharArray();
if (ch[index] == '9') {
ch[index] = '0';
} else {
ch[index] += 1;
}
return new String(ch);
}
private String minusOne(String str, int index) {
char[] ch = str.toCharArray();
if (ch[index] == '0') {
ch[index] = '9';
} else {
ch[index] -= 1;
}
return new String(ch);
}
public int openLock(String[] deadends, String target) {
Queue<String> q = new LinkedList<>();
Set<String> visited = new HashSet<>();
Set<String> dead = new HashSet<>();
for (String s : deadends) {
dead.add(s);
}
String start = "0000";
int totalTurnAtEachDigit = 4;
int impossible = -1;
q.offer(start);
visited.add(start);
int step = 0;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
String cur = q.poll();
if (target.equals(cur)) {
return step;
}
if (dead.contains(cur)) {
continue;
}
for (int j = 0; j < totalTurnAtEachDigit; j++) {
String tmpPlusOne = plusOne(cur, j);
// System.out.println("tmp up is " + tmpPlusOne);
if (!visited.contains(tmpPlusOne)) {
q.offer(tmpPlusOne);
visited.add(tmpPlusOne);
}
String tmpMinusOne = minusOne(cur,j);
// System.out.println("tmp down is " + tmpMinusOne);
if (!visited.contains(tmpMinusOne)) {
q.offer(tmpMinusOne);
visited.add(tmpMinusOne);
}
}
}
step++;
}
return impossible;
}
}