# 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

 R R R R G B G B B

then the output will be

 G G G G G B G B B

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
• 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 −

## Example

Live Demo

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
):
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))

## Input

matrix = [
["r", "r", "r"],
["r", "g", "b"],
["g", "b", "b"] ]
r = 0
c = 0
target = "g"

## Output

[ ['g', 'g', 'g'], ['g', 'g', 'b'], ['g', 'b', 'b']]

Updated on: 20-Oct-2020

150 Views 