法1:BFS
基础算法,必须掌握!!!
class Solution {
public int openLock(String[] deadends, String target) {
if ("0000".equals(target)) {
return 0;
}
Set<String> deadSet = new HashSet<>();
Set<String> usedSet = new HashSet<>();
for (String tmp : deadends) {
if ("0000".equals(tmp)) {
return -1;
}
deadSet.add(tmp);
}
int step = 0;
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
usedSet.add("0000");
while (!queue.isEmpty()) {
++step;
int size = queue.size();
for (int i = 0; i < size; ++i) { // 类似二叉树层次遍历,每层节点数量
String curStatus = queue.poll();
for (String nextTmp : nextStatus(curStatus)) {
if (!deadSet.contains(nextTmp) && !usedSet.contains(nextTmp)) {
if (nextTmp.equals(target)) {
return step;
}
queue.offer(nextTmp);
usedSet.add(nextTmp);
}
}
}
}
return -1; //无法实现返回-1
}
public List<String> nextStatus(String cur) {
List<String> res = new ArrayList<>();
char[] array = cur.toCharArray();
for (int i = 0; i < 4; ++i) {
char tmp = array[i];
char plusChar = plusOne(tmp);
char minusChar = minusOne(tmp);
array[i] = plusChar;
res.add(String.valueOf(array));
array[i] = minusChar;
res.add(String.valueOf(array));
array[i] = tmp; // 切记这里一定要复原!!!
}
return res;
}
public char plusOne(char c) {
return c == '9' ? '0' : (char) (c + 1);
}
public char minusOne(char c) {
return c == '0' ? '9' : (char) (c - 1);
}
}