BFS & DFS on Graphs and Grids — Complete Guide
Master BFS and DFS on graphs and grids: islands, flood fill, shortest paths, connected components, and multi-source BFS with 5-language implementations.
webcoderspeed.com
67 articles
Master BFS and DFS on graphs and grids: islands, flood fill, shortest paths, connected components, and multi-source BFS with 5-language implementations.
Count connected land components in a binary grid using DFS flood fill or BFS. Classic easy problem, foundation for all island variants.
Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.
Calculate the perimeter of an island in a binary grid. Each land cell contributes 4 edges minus 2 for each land neighbour.
Find the maximum area of any island in a binary grid. DFS returns the area of each island, track the maximum.
Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.
Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.
For each cell find distance to nearest 0. Multi-source BFS from all 0s simultaneously gives optimal O(m*n) solution.
Fill each empty room with distance to nearest gate. Multi-source BFS from all gates (0) simultaneously, walls (-1) are barriers.
Count land cells that cannot reach the border. Boundary DFS marks all reachable land from borders, then count remaining land cells.
Count islands in grid2 that are subsets of islands in grid1. DFS the island in grid2 and verify every cell is also land in grid1.
Find the largest island after flipping exactly one 0 to 1. Color each island with DFS, store sizes, then check each 0 cell's unique neighbour islands.
Find cells that can flow to both Pacific and Atlantic oceans. Run DFS backwards from each ocean border, find intersection.
Find shortest clear path from top-left to bottom-right in binary matrix using 8-directional BFS. Return path length or -1.
Find the water cell farthest from any land. Multi-source BFS from all land cells gives each water cell its min distance to land.
Search for a word in a grid by moving to adjacent cells without reuse. DFS with backtracking: mark visited, recurse, unmark.
Count islands with distinct shapes. Encode each island's DFS traversal path as a string to capture shape, store in a set.
Count islands fully surrounded by water (no border touch). Flood-fill border land first, then count remaining connected land components.
Find minimum flips to connect two islands. DFS to find and color first island, then BFS outward until reaching second island.
Find path from top-left to bottom-right minimizing maximum absolute difference between consecutive cells. Use Dijkstra or binary search + BFS.
Count islands after each addLand operation. Online version requires Union-Find: add each land cell and union with adjacent land cells.
Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.
Count connected components in an undirected graph given as adjacency matrix. DFS or Union-Find both work.
Determine if all rooms are reachable. Start from room 0, DFS using keys found in each room to unlock new rooms.
Check if a path exists between source and destination in an undirected graph. BFS from source or Union-Find both work in O(V+E).
BFS from entrance in a maze to find nearest exit (border empty cell). Classic BFS shortest path with exit condition.
Minimum dice rolls to reach square n^2. Convert board position to 2D coordinates (Boustrophedon order), BFS on board states.
Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.
Check if you can reach a 0 in the array by jumping arr[i] steps left or right. BFS/DFS from start index.
Determine if you can finish all courses given prerequisites. Equivalent to detecting a cycle in a directed graph using BFS (Kahn) or DFS coloring.
Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.
Check if n nodes and edges form a valid tree: must be connected and acyclic. Exactly n-1 edges, all connected via BFS/DFS or Union-Find.
Count connected components in an undirected graph. Union-Find or BFS both give O(V+E) solution.
Find the edge that creates a cycle in an undirected graph that started as a tree. Process edges with Union-Find; the first edge whose endpoints share a root is redundant.
Find all paths from node 0 to node n-1 in a DAG. DFS with backtracking: explore each path, add to results when destination reached.
Find time for signal to reach all nodes. Single-source shortest path (Dijkstra) from node k; answer is max of all shortest distances.
Find cheapest flight from src to dst with at most k stops. Bellman-Ford with k+1 iterations or BFS level-by-level.
Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.
Find ALL shortest transformation sequences. BFS builds layer map, DFS reconstructs all paths backwards from endWord to beginWord.
Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.
Check if people can be split into two groups with no dislikes within a group. Equivalent to bipartite check on dislikes graph.
Check if a graph can be 2-colored such that no adjacent nodes share a color. BFS/DFS 2-coloring on all connected components.
BFS with (position, last_jumped_back) state to find min jumps home avoiding forbidden positions. State space BFS avoids revisiting same position+direction.
Evaluate queries like A/C = A/B * B/C. Build weighted directed graph from equations, BFS/DFS to multiply edge weights along paths.
Count total reachable nodes in a subdivided graph within M moves. Dijkstra from node 0 gives max remaining moves at each node; use those to count subdivisions.
Complete cheatsheet for BFS and DFS on graphs and grids: 7 patterns, complexity table, common pitfalls, and problem index.
Build GraphRAG systems using knowledge graph traversal and vector search together to handle complex multi-hop questions and relationship-aware context retrieval.
Master advanced graph algorithms: Kruskal and Prim MST, Tarjan SCC, articulation points, bridges, Floyd-Warshall all-pairs shortest path, and A* search.
Find the minimum spanning tree of a weighted graph using Kruskal's algorithm. Sort edges by weight, use Union-Find to avoid cycles. O(E log E) time.
Build the minimum spanning tree using Prim's algorithm: start from any vertex, greedily expand by always adding the minimum-weight crossing edge using a min-heap.
Find all strongly connected components in a directed graph using Tarjan's single-pass DFS algorithm with discovery time, low-link values, and a stack.
Find all bridge edges and articulation point vertices in an undirected graph using a single DFS pass with discovery time and low-link tracking.
Compute shortest paths between all pairs of vertices using Floyd-Warshall's O(V³) DP. Handles negative weights and detects negative cycles.
Compute single-source shortest paths in graphs with negative weight edges using Bellman-Ford. V-1 relaxation passes detect negative cycles on the Vth pass.
A* combines Dijkstra's correctness with a heuristic to guide search toward the goal. Uses f(n)=g(n)+h(n) priority. Optimal when heuristic is admissible.
Advanced topological sort: DFS-based with 3-color marking for cycle detection, Kahn's BFS approach, and applications in course scheduling, build systems, and task ordering.
Advanced Dijkstra patterns: state-space Dijkstra for problems with extra constraints like K stops, fuel limit, or restricted nodes. The key is augmenting the state beyond just the node.
Check if a graph is bipartite using BFS 2-coloring. A graph is bipartite if and only if it contains no odd-length cycles — equivalent to being 2-colorable.
Connect all n points with minimum total Manhattan distance cost. Models the problem as a complete graph MST and applies optimised Prim's without building all O(n²) edges explicitly.
Find the path from source to destination minimising the maximum edge weight. Binary search on the answer + BFS/DFS connectivity check. O(E log W) total.
Count the number of shortest paths from source to destination using modified Dijkstra that tracks both minimum distance and path count simultaneously.
LeetCode 1192: Find all critical edges (bridges) in a network. A connection is critical if removing it disconnects the network. Uses Tarjan's bridge algorithm.
Find the itinerary using all flight tickets exactly once (Eulerian path). Uses Hierholzer's algorithm: DFS with post-order insertion into result — the only graph algorithm that uses post-order for path construction.
Find the minimum time to swim from (0,0) to (n-1,n-1) where you can only move to a cell when time >= cell value. Two approaches: Dijkstra O(n² log n) and binary search + BFS O(n² log n).
Find the longest path in a directed acyclic graph using DFS with memoisation. Since cycles are absent, DFS never revisits nodes, making top-down DP straightforward.
Introduction to network flow: max flow problem, Ford-Fulkerson algorithm with BFS (Edmonds-Karp), max-flow min-cut theorem, and applications in matching and connectivity.
Complete recap of all 20 advanced graph problems with algorithm selection guide, complexity comparison, and pattern recognition cues.