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 need to perform a floodfill operation at row r, column c with the target color. The floodfill operation replaces all elements that are connected to grid[r,c] (up/right/down/left) and have the same color as grid[r,c] with the target color.

Example Input and Output

If the input grid is:

R R R
R G B
G B B

Starting floodfill at position (0,0) with target color "G", the output will be:

G G G
G G B
G B B

The red cells connected to grid[0,0] are replaced with green ("g").

Algorithm Steps

To solve this problem, we follow these steps:

  • Define a set seen to track visited cells
  • Store the original color: oldcolor = matrix[r][c]
  • Create a recursive DFS function that takes coordinates (i, j)
  • Check if the current cell is valid, unvisited, and has the original color
  • If valid, mark as visited, change color to target, and recursively visit all 4 neighbors

Implementation

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[0])
                and (i, j) not in seen
                and matrix[i][j] == oldcolor
            ):
                seen.add((i, j))
                matrix[i][j] = target
                dfs(i + 1, j)  # down
                dfs(i, j + 1)  # right
                dfs(i, j - 1)  # left
                dfs(i - 1, j)  # up
        
        seen = set()
        oldcolor = matrix[r][c]
        dfs(r, c)
        return matrix

# Test the floodfill operation
ob = Solution()
matrix = [
    ["r", "r", "r"],
    ["r", "g", "b"],
    ["g", "b", "b"]
]
r = 0
c = 0
target = "g"

print("Original matrix:")
for row in matrix:
    print(row)

result = ob.solve(matrix, r, c, target)
print("\nAfter floodfill:")
for row in result:
    print(row)
Original matrix:
['r', 'r', 'r']
['r', 'g', 'b']
['g', 'b', 'b']

After floodfill:
['g', 'g', 'g']
['g', 'g', 'b']
['g', 'b', 'b']

How It Works

The algorithm uses Depth-First Search (DFS) with backtracking. Starting from the given position (r,c), it:

  1. Checks if the current cell is within bounds and has the original color
  2. Marks the cell as visited and changes its color to the target
  3. Recursively applies the same process to all four adjacent cells
  4. The seen set prevents infinite loops by tracking visited cells

Alternative Implementation Without Visited Set

We can optimize by avoiding the seen set since we're changing colors in-place:

def floodfill_optimized(matrix, r, c, target):
    oldcolor = matrix[r][c]
    
    # If target color is same as original, no change needed
    if oldcolor == target:
        return matrix
    
    def dfs(i, j):
        if (i < 0 or i >= len(matrix) or 
            j < 0 or j >= len(matrix[0]) or 
            matrix[i][j] != oldcolor):
            return
        
        matrix[i][j] = target
        dfs(i + 1, j)  # down
        dfs(i - 1, j)  # up
        dfs(i, j + 1)  # right
        dfs(i, j - 1)  # left
    
    dfs(r, c)
    return matrix

# Test optimized version
matrix2 = [
    ["r", "r", "r"],
    ["r", "g", "b"],
    ["g", "b", "b"]
]

result2 = floodfill_optimized(matrix2, 0, 0, "b")
print("Optimized floodfill result:")
for row in result2:
    print(row)
Optimized floodfill result:
['b', 'b', 'b']
['b', 'g', 'b']
['g', 'b', 'b']

Conclusion

Floodfill uses DFS to replace connected cells of the same color with a target color. The optimized version avoids using extra memory for tracking visited cells by leveraging the color changes themselves.

Updated on: 2026-03-25T11:30:35+05:30

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements