Flood Fill
An easy Graph problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Graph
- Sheets
- 3
- Core for
- 11 roles
- Platform
- LeetCode
The problem
Given an m x n binary image and a starting pixel (sr, sc), flood fill the image starting from that pixel. Replace the color of the starting pixel and all 4-directionally connected pixels of the same color with a new color.
Example 1
- Input
- image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
- Output
- [[2,2,2],[2,2,0],[2,0,1]]
- Why
- The connected region of 1s starting from (1,1) all become 2.
Example 2
- Input
- image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
- Output
- [[2,2,2],[2,2,2]]
- Why
- All pixels are connected and have the same initial color, so all become 2.
Constraints
- 1 <= image.length, image[i].length <= 50
- image[i][j] is 0 or 1
- 0 <= sr < image.length
- 0 <= sc < image[0].length
How to think about it
Updated 2026-09-09Flood fill is breadth-first or depth-first search on a grid constrained by color uniformity. Grab the starting pixel's original color before making any changes. If the target color is already equal to the original color, doing anything will spin into an infinite loop because mutating pixels never changes their visited status.
Approaches, worst first
Recursive DFS with in-place color mutation
time O(m * n) · space O(m * n)
Record `startColor = image[sr][sc]`. If `startColor === newColor`, return immediately. Otherwise, set `image[r][c] = newColor` and recurse into all 4 cardinal neighbors that match `startColor`.
Queue-based iterative BFSWrite this one
time O(m * n) · space O(m * n)
Push `(sr, sc)` to a queue after checking that `startColor !== newColor`. Dequeue points, set the cell to `newColor`, and push unvisited neighbors matching `startColor`, guaranteeing stack safety.
Where people lose marks · 3
- Invoking flood fill when `image[sr][sc] === newColor` causes infinite recursion or loop spinning if no visited check exists.
- Mutating coordinates outside bounds 0 <= r < m or 0 <= c < n before checking boundary predicates.
- Using diagonal steps; flood fill allows only 4-directional moves (up, down, left, right).
The theory behind it
Graph — the ground this problem stands on. All Graph problems
What Graph is
A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.
When to reach for it
Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.
How the pattern works
First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.
What each operation costs
| Operation | Time |
|---|---|
| visit all nodes and edges via search | O(v + e) |
| topological sort using in-degree counts | O(v + e) |
| shortest path using dijkstra with a min-heap | O((v + e) log v) |
What usually goes wrong with Graph
- Adding a node to the visited set when popping from the queue instead of when pushing, which lets neighboring nodes enqueue duplicate entries and wastes memory.
- Failing to check for cycles in directed graphs when finding prerequisite orders, causing topological sort routines to hang or return incomplete lists.
- Assuming an input graph is fully connected and scanning from only a single starting node, missing disconnected islands and isolated components.
Which roles need this problem
Graph is a core topic for these 11 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 6 more roles, including Performance Engineer, Search Engineer, Information Retrieval Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Graph problems
Problem set and role mapping as of .