Skip to main content
Back to problems
Leetcode
Easy
Arrays
Matrices
Graphs
Flood Fill

Recolor a region in a 2D image starting from one cell, replacing all connected cells of the original color.

Acceptance 100%
Problem Statement

Given a 2D integer grid representing an image, a starting cell (sr,sc)(sr, sc), and a replacement color, change the color of the starting cell and every 4-directionally connected cell with the same original color to the new color.

Two cells are connected if they share a side (up, down, left, or right). Cells with a different color act as barriers. Return the modified grid after the fill operation.

Input Format

  • A 2D integer grid image
  • Integers sr and sc for the starting row and column
  • Integer color for the new color

Output Format

Return the grid after recoloring the connected region starting at (sr, sc).

Constraints

  • 1 <= image.length, image[0].length
  • The grid size is typically small to moderate in interview settings
  • 0 <= sr < image.length
  • 0 <= sc < image[0].length
  • Cell values are integers representing colors
Examples
Sample cases returned by the problem API.

Example 1

Input

image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

Output

[[2,2,2],[2,2,0],[2,0,1]]

Explanation

The starting cell has color 1. All 4-directionally connected cells with color 1 are recolored to 2.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.