↓Skip to main content

Bfs

Tree Traversal and Common Techniques
·11 mins
Algorithm Tree Binary-Tree Dfs Bfs Bst
DFS return values, BFS level order, BST bounds, climbing to the LCA, tree diameter, and leaf trimming
BFS and Graph Traversal
·6 mins
Algorithm Bfs Dfs Graph Matrix Union-Find
Connected components, grid flood fill, multi-source BFS, state-space BFS, shortest cycles, and recursion depth in DFS
LeetCode 827: Making A Large Island
·3 mins
LeetCode Hard Dfs Bfs Matrix Union-Find
LeetCode 827 note: label every island and record its size, then for each 0 add the sizes of the distinct neighboring islands plus 1
LeetCode 3203: Find Minimum Diameter After Merging Two Trees
·3 mins
LeetCode Hard Tree Bfs Dfs Graph Tree-Diameter
LeetCode 3203 note: connect the two centers; the answer is max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1)
LeetCode 3313: Find the Last Marked Nodes in Tree
·2 mins
LeetCode Hard Tree Bfs Graph Tree-Diameter
LeetCode 3313 note: the last marked node is the farthest one, and a farthest node can always be a diameter endpoint
LeetCode 2608: Shortest Cycle in a Graph
·3 mins
LeetCode Hard Bfs Graph
LeetCode 2608 note: BFS from every node; a visited neighbor that is not the parent closes a cycle of length dist[u] + dist[v] + 1
LeetCode 987: Vertical Order Traversal of a Binary Tree
·2 mins
LeetCode Hard Tree Binary-Tree Bfs Sorting
LeetCode 987 note: collect (col, row, val) triples, sort them, and group by column
LeetCode 1210: Minimum Moves to Reach Target with Rotations
·3 mins
LeetCode Hard Bfs Matrix
LeetCode 1210 note: the BFS state is (tail position, orientation), each move checks its own empty cells, and equal step costs need no heap
LeetCode 301: Remove Invalid Parentheses
·4 mins
LeetCode Hard Backtracking Bfs String
LeetCode 301 note: compute the minimum left and right deletions before backtracking, or BFS one deletion per level and stop at the first valid level
LeetCode 864: Shortest Path to Get All Keys
·3 mins
LeetCode Hard Bfs Bit-Manipulation Matrix
LeetCode 864 note: the BFS state is (position, bitmask of keys), so the same cell with different keys is a different node
LeetCode 323: Number of Connected Components in an Undirected Graph
·2 mins
LeetCode Medium Graph Dfs Bfs Union-Find
LeetCode 323 note: count components with DFS or Union-Find; Union-Find without path compression is much slower
LeetCode 1377: Frog Position After T Seconds
·3 mins
LeetCode Hard Tree Dfs Bfs Graph Probability
LeetCode 1377 note: undirected edges, seen must hold nodes, and an early arrival depends on whether the frog can still move