Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Flood Fill

Medium Acceptance 69% Points 30

You are given a 2D grid image[][] representing an image, where each cell contains a color value. You are also given a starting cell (sr, sc) and a new color newColor. Your task is to replace the color of the starting cell and all 4-directionally connected cells having the same original color with newColor.

Cells are connected only in four directions: Up, Down, Left, Right.

Return the updated image after performing the flood fill.

Examples
Example 1

image Input: image[][] = [ [1] ] sr = 0, sc = 0, newColor = 2

Output: [ [2] ]

Explanation: The single cell is recolored.

Example 2

image 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] ]

Explanation: All connected cells with the same starting color are changed.

Example 3

image Input: image[][] = [ [0 0 0 0], [0 1 1 0], [0 1 1 0], [0 0 0 0] ] sr = 1, sc = 1, newColor = 3

Output: [ [0 0 0 0], [0 3 3 0], [0 3 3 0], [0 0 0 0] ]

Explanation: The connected region with the same color is filled with the new color.

Constraints
  • m == image.length
  • n == image[i].length
  • 1 = m, n = 50
  • 0 = image[i][j], newColor < 216
  • 0 = sr < m
  • 0 = sc < n
Topics
Recursion
Companies
Amazon Microsoft Apple Samsung Visa Walmart
Added 11 Aug 2026 69% acceptance
Ln 1, Col 1Sign in to save your code
1
1 1 1
1 1 0
1 0 1
1
1
2
2 2 2
2 2 0
2 0 1