一、题目

你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字:'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把'9'变为 '0''0' 变为'9'。每次旋转都只能旋转一个拨轮的一位数字。

锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。

列表 deadends包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。

字符串 target代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1

点击查看原题
难度级别: 中等(感觉有点困难题的意思了)

二、思路

1)BFS

首先说明为什么DFS不能使用,因为DFS会反复在同一步长范围内搜索,无法正确返回最短步长
使用BFS,可以优先记录走过的步长的字符串。在遍历的时候,令visited为访问过字符串的集合,令deadset为死锁集合,只有两个集合都没有存在的字符串,才能进行下一步访问。

三、代码

1)BFS

  1. class Solution {
  2. public int openLock(String[] deadends, String target) {
  3. Set<String> deadset = new HashSet();
  4. Set<String> visited = new HashSet();
  5. for (String s : deadends) {
  6. deadset.add(s);
  7. }
  8. if ("0000".equals(target)) {
  9. return 0;
  10. }
  11. if (deadset.contains("0000")) { // 开局死锁
  12. return -1;
  13. }
  14. int step = 1;
  15. Queue<String> q = new LinkedList();
  16. q.offer("0000");
  17. while (!q.isEmpty()) {
  18. int len = q.size();
  19. while (len-- > 0) {
  20. String s = q.poll();
  21. List<String> nextStrings = getNextStep(s); // 根据s获取下一步所有有可能字符串
  22. for (String nextString : nextStrings) {
  23. // 只有没有访问过和不死锁的字符串,才能下一步遍历
  24. if (deadset.contains(nextString) || visited.contains(nextString)) {
  25. continue;
  26. }
  27. // 在此处就确定是否为目标字符串,可以提高程序速度
  28. if (nextString.equals(target)) {
  29. return step;
  30. }
  31. q.offer(nextString);
  32. // 一定要在此添加被访问过的字符串集合,否则会成为dfs,血的教训
  33. visited.add(nextString);
  34. }
  35. }
  36. step++;
  37. }
  38. return -1;
  39. }
  40. private List<String> getNextStep(String s) {
  41. List<String> ret = new ArrayList<String>();
  42. char[] array = s.toCharArray();
  43. for (int i = 0; i < 4; ++i) {
  44. char num = array[i];
  45. array[i] = (num == '9') ? '0' : (char)(num + 1);
  46. ret.add(new String(array));
  47. array[i] = (num == '0') ? '9' : (char)(num - 1);
  48. ret.add(new String(array));
  49. array[i] = num;
  50. }
  51. return ret;
  52. }
  53. }

b是数字进制10d是数字位数4n是数组长度,时间复杂度为O(``b^d*``d^2+n*d``),空间复杂度为O(``b^d*d``+n``)