Flood Fill solution explained

To flood fill a grid, remember the color of the starting cell, and if the new color is the same, return right away. Otherwise recolor the start, then run a depth-first or breadth-first search that visits each up, down, left or right neighbor still holding the old color, recoloring it as it is added. Every cell is touched a constant number of times, so the fill is O(R × C) in the worst case and usually proportional to the size of the region.

By Published 7 min read

The problem, in plain terms

An image is stored as a grid of numbers, each number a color. You are given a starting row and column and a new color. Find every cell that has the same color as the start and can be reached from it by stepping between horizontally or vertically adjacent cells of that color, and change all of them to the new color. Cells that touch the region only at a corner are not part of it. Return the changed grid.

before          after
1 1 0 2         5 5 0 2
0 1 1 2         0 5 5 2
1 0 1 1         1 0 5 5
1 0 0 1         1 0 0 5

The two 1s in the bottom-left corner stay 1. The upper one
touches the region only diagonally, so it is not connected.
A worked example, made up for this page (start at row 0, column 0, new color 5)

Ask whether diagonals count (usually not), whether you may modify the input grid or must return a copy, how large the grid can be, and what should happen when the new color equals the starting color. The last question has a correct answer, which is to return the grid unchanged, and asking it is a strong signal.

What the interviewer looks for

Flood fill is the paint-bucket tool from any drawing program, and it is the gentlest introduction to searching a grid as a graph. Interviewers use it to check bounds handling, the choice between recursion and an explicit stack or queue, and the visited logic. The same-color case is the classic trap: without the early return, a cell recolored to the old color still matches, so the search never ends.

A slower starting idea

Without a traversal, you could mark the start as filled in a separate boolean grid and then sweep the whole grid repeatedly, marking any old-colored cell that sits next to a filled cell, until a full sweep changes nothing. Then recolor every marked cell. It is correct, but a long winding region can need one full sweep per cell of its length, which is O((R × C)²) in the worst case. The separate boolean grid matters too: if you recolor during the sweep, cells that already had the new color would look filled and leak the region. A traversal visits each cell once and avoids both issues.

The optimal approach: DFS or BFS from the start

Save old = grid[start]. If old already equals the new color, stop. Otherwise recolor the start and push it onto a stack. Repeatedly pop a cell and look at its four neighbors; any neighbor inside the grid that still holds old gets recolored immediately and pushed. Recoloring at push time, not at pop time, is what keeps a cell from being pushed twice, and it means the grid itself is the visited set, so no extra structure is needed.

def flood_fill(image, sr, sc, color):
    old = image[sr][sc]
    if old == color:
        return image               # nothing to change, and no endless loop
    rows, cols = len(image), len(image[0])
    image[sr][sc] = color
    stack = [(sr, sc)]
    while stack:
        r, c = stack.pop()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and image[nr][nc] == old:
                image[nr][nc] = color  # recolor on push, so no cell is pushed twice
                stack.append((nr, nc))
    return image
Python: iterative depth-first fill with a list as the stack.
function floodFill(image, sr, sc, color) {
  const old = image[sr][sc];
  if (old === color) return image;
  const rows = image.length, cols = image[0].length;
  const queue = [[sr, sc]];
  image[sr][sc] = color;
  for (let head = 0; head < queue.length; head++) {  // index instead of shift()
    const [r, c] = queue[head];
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] === old) {
        image[nr][nc] = color;
        queue.push([nr, nc]);
      }
    }
  }
  return image;
}
JavaScript: breadth-first fill. A moving head index replaces shift(), which is slow on long arrays.

Both give the same final grid; only the order of recoloring differs. A recursive version is shorter and fine to write first if you say its limit: Python's default recursion depth is about a thousand frames, and a single-color 600 by 600 grid has 360,000 cells in one region, so recursion would crash long before finishing. The explicit stack has no such limit.

Complexity summary

R rows, C columns, A = number of cells in the filled region
ApproachTimeExtra space
Repeated full sweeps with a boolean gridO((R × C)²) worst caseO(R × C)
Recursive DFSO(A)O(A) call stack, can overflow
Iterative DFS or BFS, recolor on pushO(A)O(A) for the stack or queue
R rows, C columns, A = number of cells in the filled region. Scroll sideways on a small screen.

Since A is at most R × C, the worst case is linear in the grid size. Cells outside the region are only looked at when they border it, so a small region in a huge image is fast.

Edge cases to test

  • New color equal to the starting color, which must return immediately.
  • A one-cell grid.
  • A region that touches all four borders, to test the bounds checks.
  • A whole grid of one color, the largest possible region.
  • Same-colored cells that touch only at corners, which must stay unchanged.
  • Other cells that already hold the new color, which must not join the region.

Mistakes that come up

  • Leaving out the old == color check, which loops forever.
  • Recoloring when a cell is popped rather than when it is pushed, which lets the same cell enter the stack several times.
  • Indexing the grid before checking bounds. In Python, a row index of -1 silently reads the last row.
  • Comparing neighbors against the new color, or against the current cell's color after it changed, instead of the saved old color.
  • Using queue.shift() in JavaScript for BFS on a big region, which can make each removal cost O(n) because the array is re-indexed.

How to explain it out loud

Fictional example

Covering the trap before the code
Candidate
First I'll save the start's color. If it already equals the new color there's nothing to do, and returning early also prevents an infinite loop.
Candidate
Otherwise I'll treat the grid as a graph and do an iterative DFS. When I push a neighbor that has the old color, I recolor it right away, so the grid itself works as my visited set.
Candidate
Each cell in the region is pushed once, so it's linear in the region's size. I'm using a stack instead of recursion because a big single-color image could blow the call stack.

Variations worth preparing

  • Eight-way connectivity: add the four diagonal steps to the neighbor list.
  • Fill with a tolerance, as image editors do: treat a neighbor as part of the region when its color is within some distance of the starting color, and track visited cells separately because the new color may also be within tolerance.
  • Return the region's size or its boundary instead of recoloring it.
  • Fill from the grid's border inward to find cells that are enclosed by another color.

The same grid walk, with a counter instead of a paint step, measures the coastline in Island Perimeter. Minimum Path Sum moves through a grid too, but only right and down, which turns it into dynamic programming rather than search. For a grid search that has to undo its marks, compare with Word Search.

Practicing flood fill with Natively

Grid problems are easy to sketch and easy to get subtly wrong. While you practice on Mac or Windows, Natively can read a grid problem from a screenshot, suggest the edge cases above, and help you trace why a fill is leaking or looping. The transcript of your practice answer lets you confirm you raised the same-color case before the interviewer had to. Learn more about AI help for coding interview practice.

Questions people ask

How do you solve Flood Fill?

Save the starting cell's color and return early if it equals the new color. Otherwise recolor the start and run a DFS or BFS that recolors and visits every side neighbor still holding the old color.

Why does Flood Fill loop forever when the new color equals the old one?

Recolored cells still match the old color, so the search keeps finding them again. Returning the grid unchanged in that case fixes it.

What is the time complexity of Flood Fill?

Proportional to the number of cells in the filled region, which is at most R × C. Extra space is the stack or queue, also bounded by the region size.

Should Flood Fill use recursion or an explicit stack?

Recursion is fine for small regions, but a large single-color region can exceed the call stack limit, especially in Python. An explicit stack or queue avoids that.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP