752. Open the Lock
破解一个由4位数字组成的锁,数字从0-9,可以顺着转,也可以反着转,从0000开始,求找到密码所转动的最小次数,同时要避开死锁。死锁是每个元素都是4位数组成的数组。
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”.
直接用bfs太慢了,时间复杂度是bd,使用双端bfs可以缩短到bd/2(b是结点数,d是每条结点的边数):
- 详细介绍:https://www.geeksforgeeks.org/bidirectional-search/
- 对0000的4个位置循环进行,每次在队列中加入2个密码,即临边,比如0000的两个邻边是1000和9000,然后是0100和0900…
- 重点在每次循环最后的起始结点和终止结点的转变
public int openLock(String[] deadends, String target) {
Set<String> begin = new HashSet<>();
Set<String> end = new HashSet<>();
Set<String> dead = new HashSet<>(Arrays.asList(deadends));
begin.add("0000");
end.add(target);
int count = 0;
while (!begin.isEmpty() && !end.isEmpty()) {
Set<String> temp = new HashSet<>();
for (String s : begin) {
if (end.contains(s))
return count;
if (dead.contains(s))
continue;
dead.add(s);
StringBuffer str = new StringBuffer(s);
for (int i = 0; i < 4; i++) {
char ch = s.charAt(i);
String s1 = str.substring(0, i) + (ch == '9'? 0 : ch - '0' + 1) + str.substring(i+1);
String s2 = str.substring(0, i) + (ch == '0'? 9 : ch - '0' - 1) + str.substring(i+1);
if (!dead.contains(s1))
temp.add(s1);
if ((!dead.contains(s2)))
temp.add(s2);
}
}
//双端bfs算法,从源结点向目标结点搜索,同时从目标结点向源结点搜索
begin = end;
end = temp;
count++;
}
return -1;
}