leetcode 752. Open the Lock | 752. 打开转盘锁(BFS)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                leetcode 752. Open the Lock | 752. 打开转盘锁(BFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題目
https://leetcode.com/problems/open-the-lock/
 
題解
先寫了個 DFS,超時了。
看了下 Related Topics,提示說應該是 BFS。這已經不是第一次遇到 BFS 可以、DFS 超時的題目了。
總結了一下,對于這種可以用 DFS/BFS 求最短路徑的題目,優先選擇 BFS,因為你到達目標的可能性有超級多種,而大多數路線都走了很多彎路,去遍歷它們都是無用功。用 BFS 的話,從 step=1 開始逐漸遞增,在 step 受限的情況下,只要到達了目標,當前 step 一定是最短的 step。
另外,本題可以使用 智能算法(只是想到了,沒有嘗試過)(遺傳/蟻群) / 啟發式搜索(答案提到了,例如 A*)來做,作為拓展思路,本文不作實現。
class Solution {public int openLock(String[] deadends, String target) {int t = Integer.parseInt(target);Set<Integer> block = new HashSet<>();for (String s : deadends) {block.add(Integer.parseInt(s));}Set<Integer> seen = new HashSet<>();Stack<Integer> stack = new Stack<>();stack.push(0);int step = 0;while (!stack.isEmpty()) {Stack<Integer> nextStack = new Stack<>();while (!stack.isEmpty()) {int cur = stack.pop();if (cur == t) return step;if (block.contains(cur) || seen.contains(cur)) continue;seen.add(cur);nextStack.add(move(cur, 0, true));nextStack.add(move(cur, 0, false));nextStack.add(move(cur, 1, true));nextStack.add(move(cur, 1, false));nextStack.add(move(cur, 2, true));nextStack.add(move(cur, 2, false));nextStack.add(move(cur, 3, true));nextStack.add(move(cur, 3, false));}step++;stack = nextStack;}return -1;}public int move(int cur, int index, boolean front) {int[] arr = new int[4];int i = 3;while (cur != 0) {arr[i] = cur % 10;cur /= 10;i--;}arr[index] = front ? ((arr[index] + 1) + 10) % 10 : ((arr[index] - 1) + 10) % 10;int result = 0;for (int j = 0; j < 4; j++) {result *= 10;result += arr[j];}return result;} }總結
以上是生活随笔為你收集整理的leetcode 752. Open the Lock | 752. 打开转盘锁(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: leetcode 743. Networ
 - 下一篇: leetcode 797. All Pa