Leetcode 733: Flood Fill

grid47
grid47
Exploring patterns and algorithms
Aug 25, 2024 6 min read

A grid where the flood fill algorithm is applied, with the flooded area glowing softly as it spreads.
Solution to LeetCode 733: Flood Fill Problem

You are given an m x n grid representing an image, where each element in the grid corresponds to a pixel value. Additionally, you’re provided with three integers: sr (starting row), sc (starting column), and color. Your task is to perform a flood fill operation on the image starting at the pixel located at (sr, sc).
Problem
Approach
Steps
Complexity
Input: You are given a 2D grid representing an image, three integers sr, sc, and color.
Example: image = [[1, 1, 1], [1, 1, 0], [1, 0, 1]], sr = 1, sc = 1, color = 2
Constraints:
• m == image.length
• n == image[i].length
• 1 <= m, n <= 50
• 0 <= image[i][j], color < 216
• 0 <= sr < m
• 0 <= sc < n
Output: Return the modified image after performing the flood fill.
Example: After performing the flood fill on the input image, return the modified grid.
Constraints:
Goal: Change the color of the starting pixel and recursively change the color of adjacent pixels that share the original color.
Steps:
• Check if the color to be applied is the same as the starting pixel's color.
• If different, perform a DFS (depth-first search) to apply the flood fill to all connected pixels that have the same original color.
Goal: Ensure that the grid's bounds and pixel values are respected.
Steps:
• The image grid's dimensions must be between 1x1 and 50x50.
• The pixel values and target color must be in the range [0, 215].
• The starting point must be within the bounds of the grid.
Assumptions:
• The grid will always contain at least one element.
• The target color will not be equal to the original color if the flood fill is to occur.
Input: Starting from (1, 1) and applying the color 2 results in a flood fill of the connected pixels.
Explanation: Starting from pixel (1, 1) with color 1, all connected pixels with color 1 will be changed to color 2. This process stops when there are no more pixels connected to the starting pixel with the same original color.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus