Learn DSA
Two Pointers
Sliding Window
Intervals
Stack
Linked List
Binary Search
Heap
Depth-First Search
Breadth-First Search
Backtracking
Graphs
Dynamic Programming
Greedy Algorithms
Trie
Prefix Sum
Matrices
Flood Fill
DESCRIPTION (credit Leetcode.com)
Given a m x n integer grid image and integers sr, sc, and newColor, write a function to perform a flood fill on the image starting from the pixel image[sr][sc].
In a 'flood fill', start by changing the color of image[sr][sc] to newColor. Then, change the color of all pixels connected to image[sr][sc] from either the top, bottom, left or right that have the same color as image[sr][sc], along with all the connected pixels of those pixels, and so on.
EXAMPLES
Input: image = [[1,0,1],[1,0,0],[0,0,1]], sr = 1, sc = 1, color = 2
Output: [[1,2,1],[1,2,2],[2,2,1]]
The zeroes connected to the starting pixel (1, 1) are colored with the new color (2).
Run your code to see results here
Explanation
def flood_fill(image, sr, sc, color):rows, cols = len(image), len(image[0])original_color = image[sr][sc]if original_color == color:return imagedef dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)returndfs(sr, sc)return image
def dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)return
def flood_fill(image, sr, sc, color):rows, cols = len(image), len(image[0])original_color = image[sr][sc]if original_color == color:return imagedef dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)returndfs(sr, sc)return image
def dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)return
def dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)return
def dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)return
Animated Solution
def flood_fill(image, sr, sc, color):rows, cols = len(image), len(image[0])original_color = image[sr][sc]if original_color == color:return imagedef dfs(r, c):if image[r][c] == original_color:image[r][c] = colorif r >= 1: dfs(r - 1, c)if r + 1 < rows: dfs(r + 1, c)if c >= 1: dfs(r, c - 1)if c + 1 < cols: dfs(r, c + 1)returndfs(sr, sc)return image
Loading comments...