leetcode 752. Open the Lock | 752. 打开转盘锁(BFS)

x33g5p2x  于2021-11-27 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(325)

题目

https://leetcode.com/problems/open-the-lock/

题解

先写了个 DFS,超时了。

看了下 Related Topics,提示说应该是 BFS。这已经不是第一次遇到 BFS 可以、DFS 超时的题目了。

总结了一下,对于这种可以用 DFS/BFS 求最短路径的题目,优先选择 BFS,因为你到达目标的可能性有超级多种,而大多数路线都走了很多弯路,去遍历它们都是无用功。用 BFS 的话,从 step=1 开始逐渐递增,在 step 受限的情况下,只要到达了目标,当前 step 一定是最短的 step。

另外,本题可以使用 智能算法(只是想到了,没有尝试过)(遗传/蚁群) / 启发式搜索(答案提到了,例如 A*)来做,作为拓展思路,本文不作实现。

  1. class Solution {
  2. public int openLock(String[] deadends, String target) {
  3. int t = Integer.parseInt(target);
  4. Set<Integer> block = new HashSet<>();
  5. for (String s : deadends) {
  6. block.add(Integer.parseInt(s));
  7. }
  8. Set<Integer> seen = new HashSet<>();
  9. Stack<Integer> stack = new Stack<>();
  10. stack.push(0);
  11. int step = 0;
  12. while (!stack.isEmpty()) {
  13. Stack<Integer> nextStack = new Stack<>();
  14. while (!stack.isEmpty()) {
  15. int cur = stack.pop();
  16. if (cur == t) return step;
  17. if (block.contains(cur) || seen.contains(cur)) continue;
  18. seen.add(cur);
  19. nextStack.add(move(cur, 0, true));
  20. nextStack.add(move(cur, 0, false));
  21. nextStack.add(move(cur, 1, true));
  22. nextStack.add(move(cur, 1, false));
  23. nextStack.add(move(cur, 2, true));
  24. nextStack.add(move(cur, 2, false));
  25. nextStack.add(move(cur, 3, true));
  26. nextStack.add(move(cur, 3, false));
  27. }
  28. step++;
  29. stack = nextStack;
  30. }
  31. return -1;
  32. }
  33. public int move(int cur, int index, boolean front) {
  34. int[] arr = new int[4];
  35. int i = 3;
  36. while (cur != 0) {
  37. arr[i] = cur % 10;
  38. cur /= 10;
  39. i--;
  40. }
  41. arr[index] = front ? ((arr[index] + 1) + 10) % 10 : ((arr[index] - 1) + 10) % 10;
  42. int result = 0;
  43. for (int j = 0; j < 4; j++) {
  44. result *= 10;
  45. result += arr[j];
  46. }
  47. return result;
  48. }
  49. }

相关文章