Created
December 10, 2021 11:38
-
-
Save 9helix/6b350ffa706e7c495d589e40df7b0f44 to your computer and use it in GitHub Desktop.
Flood Fill Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def floodfill(grid, row, col, newColor): | |
oldColor = grid[row][col] | |
if newColor == oldColor: | |
return grid | |
recurse(grid, row, col, newColor, oldColor) | |
return grid | |
def recurse(grid, row, col, newColor, oldColor): | |
if grid[row][col] != oldColor: | |
return | |
grid[row][col] = newColor | |
if row != 0: | |
recurse(grid, row-1, col, newColor, oldColor) | |
if col != 0: | |
recurse(grid, row, col-1, newColor, oldColor) | |
if row != len(grid)-1: | |
recurse(grid, row+1, col, newColor, oldColor) | |
if col != len(grid[0])-1: | |
recurse(grid, row, col+1, newColor, oldColor) | |
def gridprint(grid): | |
for i in range(len(grid)): | |
for j in range(len(grid[i])): | |
if j == len(grid[i])-1: | |
print(grid[i][j]) | |
else: | |
print(grid[i][j], end=' ') | |
oldgrid = [[1, 1, 1], [1, 1, 0], [1, 0, 1]] | |
newgrid = floodfill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2) | |
gridprint(oldgrid) | |
print() | |
gridprint(newgrid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment