↓Skip to main content

Graph

LeetCode 834: Sum of Distances in Tree
·3 mins
LeetCode Hard Dynamic-Programming Tree Depth-First-Search Graph Dp-on-Trees
LeetCode 834 note: rerooting DP: compute subtree sizes and ans[0] with root 0, then push ans[child] = ans[parent] - size + (n - size) to every node
LeetCode 2858: Minimum Edge Reversals So Every Node Is Reachable
·2 mins
LeetCode Hard Dynamic-Programming Depth-First-Search Breadth-First-Search Graph
LeetCode 2858 note: rerooting DP: count the reversals needed with root 0, then moving the root to a child adds 1 if that edge pointed down and subtracts 1 if it pointed up
LeetCode 3787: Find Diameter Endpoints of a Tree
·2 mins
LeetCode Medium Tree Breadth-First-Search Graph
LeetCode 3787 note: two BFS passes find one diameter’s ends A and B; every node’s farthest node is A or B, so a node is a diameter endpoint exactly when max(dist(A,i), dist(B,i)) equals the diameter
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 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
Topological Sort
·3 mins
Algorithm Graph Topological-Sort Kahn
Ordering, cycle detection, dependency unlocking, and graph propagation
Shortest Path
·3 mins
Algorithm Graph Shortest-Path Dijkstra Bellman-Ford
Dijkstra, minimax paths, and Bellman-Ford with edge limits
LeetCode 4046: Minimum Cost Path With At Most K Turns
·3 mins
LeetCode Hard Graph Shortest-Path Heap Matrix
LeetCode 4046 note: Dijkstra with the last direction and the turns used in the state; for the same cell and direction, an earlier pop is cheaper, and if it also used fewer turns it dominates later states
LeetCode 499: The Maze III
·3 mins
LeetCode Hard Graph Dijkstra Shortest-Path Heap Matrix
LeetCode 499 note: Dijkstra prioritized by (distance, path string), and the ball stops when it rolls over the hole
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