Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Flood Fill

Graphseasy

Given an `image` grid, a start pixel `(sr, sc)`, and a `newColor`, implement `floodFill(image, sr, sc, newColor)` that fills the connected region of the start pixel's color with `newColor`. Return the image.

Sample tests

Input: floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2)
Output: [[2,2,2],[2,2,0],[2,0,1]]
Input: floodFill([[0,0,0],[0,0,0]], 0, 0, 0)
Output: [[0,0,0],[0,0,0]]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Not guarding equal new and old color causes infinite recursion.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

Recursive flood fill repaints the connected region in O(rows * cols) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.