766. Flood Fill Algorithm

MediumRecursionRecursion

You are given an m x n integer grid image representing a picture, along with three integers: sr, sc, and color. Starting from the pixel at (sr, sc), flood-fill the image: change the color of (sr, sc) and every 4-directionally connected pixel of the same original color to the given color. Return the modified image. Input is a JSON object with fields image, sr, sc, and color. If the starting pixel's color already equals color, return the image unchanged.

Input: A JSON object: {"image":[[...]],"sr":r,"sc":c,"color":v}.

Output: Return the modified grid as a JSON 2D array.

Examples

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: All connected 1s reachable from (1,1) become 2.
Example 2
Input: {"image":[[0,0,0],[0,0,0]],"sr":0,"sc":0,"color":2}
Output: [[2,2,2],[2,2,2]]
Explanation: Entire grid is connected 0s.
Example 3
Input: {"image":[[1,1],[1,1]],"sr":0,"sc":0,"color":1}
Output: [[1,1],[1,1]]
Explanation: Already that color; no change.

Constraints

Asked by

AmazonAppleMicrosoftBloombergGoogleOracle
Solve this problem in the editor →