DEV Community

Cover image for Leetcode 733. Flood Fill
codingpineapple
codingpineapple

Posted on

Leetcode 733. Flood Fill

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]]
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay