↓快轉到主要內容

Bfs

Tree 樹的遍歷與常見技巧
·7 分鐘
演算法 Tree Binary-Tree Dfs Bfs Bst
DFS 回傳值、BFS 層序、BST 上下界、往上找 LCA、樹的直徑與剪葉子
BFS 與圖的遍歷
·3 分鐘
演算法 Bfs Dfs Graph Matrix Union-Find
連通塊、網格 flood fill、多源 BFS、狀態空間 BFS、最短環,以及遞迴 DFS 的深度問題
LeetCode 827: Making A Large Island
·2 分鐘
LeetCode Hard Dfs Bfs Matrix Union-Find
LeetCode 827 解題筆記:先幫每座島編號並記大小,再對每個 0 看四周有哪些不同的島,大小相加再加 1
LeetCode 3203: Find Minimum Diameter After Merging Two Trees
·2 分鐘
LeetCode Hard Tree Bfs Dfs Graph Tree-Diameter
LeetCode 3203 解題筆記:連接兩棵樹的中心,答案是 max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1)
LeetCode 3313: Find the Last Marked Nodes in Tree
·1 分鐘
LeetCode Hard Tree Bfs Graph Tree-Diameter
LeetCode 3313 解題筆記:最後被標記的就是最遠的點,而最遠點一定能取直徑端點
LeetCode 2608: Shortest Cycle in a Graph
·2 分鐘
LeetCode Hard Bfs Graph
LeetCode 2608 解題筆記:從每個點 BFS,遇到已拜訪而且不是 parent 的鄰居,就找到一個長度 dist[u] + dist[v] + 1 的環
LeetCode 987: Vertical Order Traversal of a Binary Tree
·1 分鐘
LeetCode Hard Tree Binary-Tree Bfs Sorting
LeetCode 987 解題筆記:收集 (欄, 列, 值) 三元組,排序後依欄分組
LeetCode 1210: Minimum Moves to Reach Target with Rotations
·2 分鐘
LeetCode Hard Bfs Matrix
LeetCode 1210 解題筆記:BFS 的狀態是 (蛇尾位置, 方向),四種移動各自檢查需要空的格子;每步成本相同不需要 heap
LeetCode 301: Remove Invalid Parentheses
·2 分鐘
LeetCode Hard Backtracking Bfs String
LeetCode 301 解題筆記:先算出最少要刪幾個左右括號再回溯;或用 BFS 一層刪一個,第一個出現合法字串的層就是答案
LeetCode 864: Shortest Path to Get All Keys
·2 分鐘
LeetCode Hard Bfs Bit-Manipulation Matrix
LeetCode 864 解題筆記:BFS 的狀態是 (位置, 拿到的鑰匙遮罩),同一格拿著不同鑰匙是不同的節點
LeetCode 323: Number of Connected Components in an Undirected Graph
·2 分鐘
LeetCode Medium Graph Dfs Bfs Union-Find
LeetCode 323 解題筆記:DFS 或 Union-Find 數連通塊;Union-Find 沒有路徑壓縮會慢很多
LeetCode 1377: Frog Position After T Seconds
·2 分鐘
LeetCode Hard Tree Dfs Bfs Graph Probability
LeetCode 1377 解題筆記:無向邊、seen 要記節點、提早到達目標時要看還能不能走