- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to fill with color using floodfill operation in Python
Suppose we have a 2D grid, containing colors as strings "r", "g", and "b". We have to perform floodfill operation at row r, column c with the color target. As we know the Floodfill operation should replace all elements that are both connected to grid[r,c] (up/right/down/left) and have the same color as grid[r,c] with the same color as target.
So, if the input is like
then the output will be
as the red cells connected to grid[0,0] are replaced with green ("g").
To solve this, we will follow these steps −
- define a new set seen
- oldcolor := matrix[r, c]
- Define a function dfs() . This will take i, j
- if i and j are in the matrix and (i, j) is not seen and matrix[i, j] is same as oldcolor, then
- add(i, j) of seen
- matrix[i, j] := target
- dfs(i + 1, j)
- dfs(i, j + 1)
- dfs(i, j - 1)
- dfs(i - 1, j
- From the main method, do the following −
- dfs(r, c)
- return matrix
Let us see the following implementation to get better understanding −
class Solution: def solve(self, matrix, r, c, target): def dfs(i, j): if ( i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix) and (i, j) not in seen and matrix[i][j] == oldcolor ): seen.add((i, j)) matrix[i][j] = target dfs(i + 1, j) dfs(i, j + 1) dfs(i, j - 1) dfs(i - 1, j) seen = set() oldcolor = matrix[r][c] dfs(r, c) return matrix ob = Solution() matrix = [ ["r", "r", "r"], ["r", "g", "b"], ["g", "b", "b"] ] r = 0 c = 0 target = "g" print(ob.solve(matrix, r, c, target))
matrix = [ ["r", "r", "r"], ["r", "g", "b"], ["g", "b", "b"] ] r = 0 c = 0 target = "g"
[ ['g', 'g', 'g'], ['g', 'g', 'b'], ['g', 'b', 'b']]
- How to fill color above the curve in Matplotlib Program?
- Flood fill to specific color in PHP using imagefilltoborder() (GD) function.
- How to fill rainbow color under a curve in Python Matplotlib?
- Program to perform XOR operation in an array using Python
- How to fill the outliers with different color in base R boxplot?
- How to fill color below a curve in Matplotlib?
- Program to perform excel spreadsheet operation in Python?
- Program to determine color of a chessboard square using Python
- Program to fill Min-max game tree in Python
- Program to partition color list in Python
- Java Program to fill an array with random numbers
- Program to convert one list identical to other with sublist sum operation in Python
- Fill username and password using selenium in python.
- Python Pandas - Fill NaN with Linear Interpolation
- Python Pandas - Fill NaN with Polynomial Interpolation