Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Flood Fill

Medium Acceptance 69.00% Points 30.00

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.

Hints
Hint 1
N/A
Constraints
  • m == image.length
  • n == image[i].length
  • 1 = m, n = 50
  • 0 = image[i][j], newColor < 216
  • 0 = sr < m
  • 0 = sc < n
Companies
Amazon Microsoft Apple Samsung Visa + 1 more
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions