1.Flood fill
IntermediateStarting from cell (1, 1), change that cell and every connected cell (up, down, left, right) of the same colour to colour 2, like a paint bucket tool. Grid [[1, 1, 1], [1, 1, 0], [1, 0, 1]]. Print the rows.
Show hint
DFS with an explicit stack from the start cell. Record the original colour first, and stop if it already equals the new colour.
Show solution
def flood_fill(grid, r, c, new):
old = grid[r][c]
if old == new:
return grid
stack = [(r, c)]
while stack:
i, j = stack.pop()
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == old:
grid[i][j] = new
stack.extend([(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)])
return grid
for row in flood_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2):
print(row)[2, 2, 2]
[2, 2, 0]
[2, 0, 1]The bottom-right 1 is not connected to the start (only diagonally), so it keeps its colour.