Bfs

83 articles

dsa2 min read

Flood Fill — DFS Color Replace

Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.

Read →
dsa2 min read

Surrounded Regions — Boundary DFS

Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.

Read →
dsa2 min read

Rotting Oranges — Multi-Source BFS

Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.

Read →
dsa2 min read

Clone Graph — BFS/DFS with HashMap

Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.

Read →
dsa1 min read

Open the Lock — BFS State Space

Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.

Read →
dsa1 min read

Course Schedule II — Topological Order

Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.

Read →
dsa2 min read

Word Ladder — BFS Shortest Transformation

Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.

Read →
dsa1 min read

Bus Routes — BFS on Route Graph

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.

Read →
dsa3 min read

Trapping Rain Water II

Calculate trapped water in a 3D height map using BFS with a min-heap to process cells from shortest boundary inward.

Read →
dsa1 min read

Kth Largest Sum in a Binary Tree

Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.

Read →
dsa3 min read

Maximum Width of Binary Tree

Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.

Read →
dsa2 min read

Add One Row to Tree

Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.

Read →
dsa1 min read

Deepest Leaves Sum

Sum all nodes at the deepest level of a binary tree using BFS to process level by level.

Read →
dsa2 min read

Cousins in Binary Tree

Determine if two nodes are cousins (same depth, different parents) using BFS to track depth and parent.

Read →
dsa1 min read

Graph Coloring and Bipartite Check

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.

Read →