Tensorum
LeetCode 733 · Graph Fundamentals / DFS

Flood Fill

LeetCode 733 · Easy · solution, intuition & step-by-step walkthrough

DFS through cells of the starting colour.

EasyArrayDepth-First SearchBreadth-First SearchMatrix
0 msruntime · beats 100%
20.8 MBmemory · beats 6%
1approach
9accepted runs · last 17 Sept 2026

This is how I solved Flood Fill (LeetCode 733), an easy problem from the Graph Fundamentals / DFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.

Approach

  1. 1

    Remember the starting colour.

  2. 2

    DFS: paint the cell, recurse into same-coloured unvisited neighbours.

How I solved it

Grid DFSPythonO(m·n) time
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        m = len(image)
        n = len(image[0])
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        default_color = image[sr][sc]
        visited = set()
        visited.add((sr,sc))
        def dfs(row,col):
            visited.add((row,col))
            image[row][col]=color
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and image[nrow][ncol]==default_color and (nrow,ncol) not in visited:
                    dfs(nrow,ncol)
        dfs(sr,sc)
        return image

        
Loading the step-through…

Flood Fill — FAQ

What is the intuition behind Flood Fill?

Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.

How do you solve Flood Fill (LeetCode 733)?

1. Remember the starting colour. 2. DFS: paint the cell, recurse into same-coloured unvisited neighbours.

What is the time and space complexity of Flood Fill?

Time: O(m · n). Space: O(m · n). (Accepted approach: Grid DFS.)

What are common mistakes in Flood Fill?

If the new colour equals the old one, a visited set (or early return) prevents infinite loops.