forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0752-open-the-lock.java
48 lines (46 loc) · 1.9 KB
/
0752-open-the-lock.java
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
//Simple BFS solution
classSolution {
publicintopenLock(String[] deadends, Stringtarget) {
Stringstart = "0000";
intans = 0;
Queue<String> q = newLinkedList<>();
HashSet<String> visited = newHashSet<>();
//Add all the deadends in the visited set so we can ignore them and visited values altogether.
for (Strings : deadends) visited.add(s);
q.offer(start);
while (!q.isEmpty()) {
intsize = q.size();
for (intj = 0; j < size; j++) {
Stringstr = q.poll();
StringBuildercur = newStringBuilder(str);
if (str.equals(target)) returnans;
if (!visited.contains(cur.toString())) {
for (inti = 0; i < start.length(); i++) {
//edge case for 0
if (cur.charAt(i) == '0') {
cur.setCharAt(i, '1');
q.offer(cur.toString());
cur.setCharAt(i, '9');
q.offer(cur.toString());
} elseif (cur.charAt(i) == '9') { //edge case for 9
cur.setCharAt(i, '0');
q.offer(cur.toString());
cur.setCharAt(i, '8');
q.offer(cur.toString());
} else {
cur.setCharAt(i, ((char) (cur.charAt(i) + 1)));
q.offer(cur.toString());
cur.setCharAt(i, ((char) (cur.charAt(i) - 2)));
q.offer(cur.toString());
}
visited.add(str);
cur.setLength(0);
cur.append(str);
}
}
}
ans++;
}
return -1;
}
}