Description
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.
Examples
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 cannot reach the target without getting stuck.
Constraints:
1 <= deadends.length <= 500 deadends[i].length == 4 target.length == 4 target will not be in the list deadends. target and deadends[i] consist of digits only.
思路
可以当作graph search中的shortest path search来做,也就是用bfs,每个String都是一个state,如果有deadend就不存在这个节点
需要注意的是如果deadend中存在0000,可以直接返回-1,target是0000可以直接返回0
代码
class Solution {
public String sub(String a, int pos) {
char[] chs = a.toCharArray();
chs[pos] = chs[pos] > '0'? (char)(chs[pos] - 1): '9';
return String.valueOf(chs);
}
public String add(String a, int pos) {
char[] chs = a.toCharArray();
chs[pos] = chs[pos] < '9'? (char)(chs[pos] + 1): '0';
return String.valueOf(chs);
}
public int openLock(String[] deadends, String target) {
if (target.equals("0000"))
return 0;
List<String> currLayer = new ArrayList<>();
Set<String> hasVisited = new HashSet<>();
for (String deadend: deadends)
hasVisited.add(deadend);
currLayer.add("0000");
if (hasVisited.contains("0000"))
return -1;
hasVisited.add("0000");
int count = 1;
while(currLayer.size() != 0) {
List<String> nextLayer = new ArrayList<>();
for (String currNum: currLayer){
for (int i = 0; i < 4; i++) {
String subS = sub(currNum, i);
String addS = add(currNum, i);
if (subS.equals(target) || addS.equals(target))
return count;
if (!hasVisited.contains(subS)) {
hasVisited.add(subS);
nextLayer.add(subS);
}
if (!hasVisited.contains(addS)) {
hasVisited.add(addS);
nextLayer.add(addS);
}
}
}
count ++;
currLayer = nextLayer;
}
return -1;
}
}
|