https://leetcode.com/problems/open-the-lock/description/
X.
https://leetcode.com/problems/open-the-lock/discuss/112946/54ms-Java-2-end-BFS-Solution
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots:
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
. The wheels can rotate freely and wrap around: for example we can turn '9'
to be '0'
, or '0'
to be '9'
. Each move consists of turning one wheel one slot.
The lock initially starts at
'0000'
, a string representing the state of the 4 wheels.
You are given a list of
deadends
dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a
target
representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
Example 1:
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102".
Example 2:
Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
Example 3:
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We can't reach the target without getting stuck.
Example 4:
Input: deadends = ["0000"], target = "8888" Output: -1
Note:
- The length of
deadends
will be in the range[1, 500]
. target
will not be in the listdeadends
.- Every string in
deadends
and the stringtarget
will be a string of 4 digits from the 10,000 possibilities'0000'
to'9999'
.
https://leetcode.com/problems/open-the-lock/discuss/112946/54ms-Java-2-end-BFS-Solution
public int openLock(String[] deadends, String target) {
if (target.equals("0000")) return 0;
int res = 0;
Set<String> visited = new HashSet<>(), tset = new HashSet<>(), zset = new HashSet<>();
visited.addAll(Arrays.asList(deadends));
if (visited.contains("0000")) return -1;
zset.add("0000");
tset.add(target);
while (zset.size() > 0 && tset.size() > 0) {
Set<String> set = zset.size() > tset.size() ? tset : zset;
Set<String> other = zset.size() > tset.size() ? zset : tset;
Set<String> next = new HashSet<>();
res++;
for (String s: set) {
visited.add(s);
char[] sa = s.toCharArray();
// four digit
for (int i = 0; i < 4; i++) {
// increase
if (sa[i]++ == '9') sa[i] = '0';
String t = new String(sa);
if (other.contains(t)) return res;
if (!visited.contains(t)) next.add(t);
if (sa[i]-- == '0') sa[i] = '9';
// decrease
if (sa[i]-- == '0') sa[i] = '9';
t = new String(sa);
if (other.contains(t)) return res;
if (!visited.contains(t)) next.add(t);
if (sa[i]++ == '9') sa[i] = '0';
}
}
if (zset.size() > tset.size()) tset = next;
else zset = next;
}
return -1;
}
https://leetcode.com/problems/open-the-lock/discuss/110247/JavaC++-Clean-Code public int openLock(String[] deadends, String target) {
Set<String> dead = new HashSet<>();
for (String s : deadends) dead.add(s);
if (dead.contains("0000")) return -1;
if ("0000".equals(target)) return 0;
Set<String> v = new HashSet<>();
Queue<String> q = new LinkedList<>();
q.add("0000");
for (int d = 1; !q.isEmpty(); d++) {
for (int n = q.size(); n > 0; n--) {
String cur = q.poll();
for (int i = 0; i < 4; i++) {
for (int dif = 1; dif <= 9; dif += 8) {
char[] ca = cur.toCharArray();
ca[i] = (char)((ca[i] - '0' + dif) % 10 + '0');
String s = new String(ca);
if (target.equals(s)) return d;
if (!dead.contains(s) && !v.contains(s)) q.add(s);
v.add(s);
}
}
}
}
return -1;
}
https://leetcode.com/problems/open-the-lock/discuss/110232/Accepted-PythonJava-BFS-+-how-to-avoid-TLE
Shortest path finding, when the weights are constant, as in this case = 1, BFS is the best way to go.
Best way to avoid TLE is by using deque and popleft() .
[Using list() and pop(0) is a linear operation in Python, resulting in TLE]
Best way to avoid TLE is by using deque and popleft() .
[Using list() and pop(0) is a linear operation in Python, resulting in TLE]
public static int openLock(String[] deadends, String target) {
Queue<String> q = new LinkedList<>();
Set<String> deads = new HashSet<>(Arrays.asList(deadends));
Set<String> visited = new HashSet<>();
int depth = 0;
String marker = "*";
q.addAll(Arrays.asList("0000", "*"));
while(!q.isEmpty()) {
String node = q.poll();
if(node.equals(target))
return depth;
if(visited.contains(node) || deads.contains(node))
continue;
if(node.equals(marker) && q.isEmpty())
return -1;
if(node.equals(marker)) {
q.add(marker);
depth += 1;
} else {
visited.add(node);
q.addAll(getSuccessors(node));
}
}
return depth;
}
private static List<String> getSuccessors(String str) {
List<String> res = new LinkedList<>();
for (int i = 0; i < str.length(); i++) {
res.add(str.substring(0, i) + (str.charAt(i) == '0' ? 9 : str.charAt(i) - '0' - 1) + str.substring(i+1));
res.add(str.substring(0, i) + (str.charAt(i) == '9' ? 0 : str.charAt(i) - '0' + 1) + str.substring(i+1));
}
return res;
}
public int openLock(String[] deadends, String target) {
String start = "0000";
Map<String, Integer> steps = new HashMap<>();
for (String deadend : deadends) {
steps.put(deadend, Integer.MAX_VALUE);
}
if (steps.containsKey(start)) {
return -1;
}
Queue<String> queue = new ArrayDeque<>();
queue.add(start);
steps.put(start, 0);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String cur = queue.poll();
if (cur.equals(target)) {
return steps.get(cur);
}
addNbs(cur, queue, steps);
}
}
return -1;
}
private void addNbs(String cur, Queue<String> queue, Map<String, Integer> steps) {
int step = steps.get(cur);
char[] curArray = cur.toCharArray();
for (int i = 0; i < cur.length(); i++) {
char old = curArray[i];
curArray[i] = (char) (old + 1);
if (curArray[i] > '9') {
curArray[i] = '0';
}
add(String.valueOf(curArray), queue, steps, step);
curArray[i] = (char) (old - 1);
if (curArray[i] < '0') {
curArray[i] = '9';
}
add(String.valueOf(curArray), queue, steps, step);
curArray[i] = old;
}
}
private void add(String string, Queue<String> queue, Map<String, Integer> steps, int step) {
if (steps.containsKey(string))
return;
queue.add(string);
steps.put(string, step + 1);
}