codingpineapple

Posted on

# Description:

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.

To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.

# Example 1:

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

# Solution:

Time Complexity: O(n)
Space Complexity: O(n)

``````// We will find the first cell to paint using the
// provided coordinates
// We call our recursive fill function on that cell
// The fill function will call itself on the cells that are on top,
// bottom, and to the left and right of the original cell if those
// cells have the same color as the original cell

var floodFill = function(image, sr, sc, newColor) {
const oldColor = image[sr][sc];
fill(image, sr, sc, newColor, oldColor);
return image;
};

function fill(image, sr, sc, newColor, oldColor) {
if(image[sr][sc]===oldColor) {
image[sr][sc] = newColor
//top
if(sr >= 1) fill(image, sr-1, sc, newColor, oldColor);
// bottom
if(sr+1 < image.length) fill(image, sr+1, sc, newColor, oldColor);
// left
if(sc >= 1) fill(image, sr, sc-1, newColor, oldColor);
// right
if(sc+1 < image[0].length) fill(image, sr, sc+1, newColor, oldColor);
}
}
``````