Skip to content

Instantly share code, notes, and snippets.

@tomrockdsouza
Last active December 27, 2024 15:58
Show Gist options
  • Save tomrockdsouza/641d8e6bb6f56ac4220b2036d83ee96c to your computer and use it in GitHub Desktop.
Save tomrockdsouza/641d8e6bb6f56ac4220b2036d83ee96c to your computer and use it in GitHub Desktop.
Recursive List Based 8 Flood Fill
# python.exe .\fill.py --rows=9 --cols=9 --x=8 --y=5
import fire
def create_image(rows, cols):
def is_prime(num):
for x in reversed(range(2, num)):
if num % x == 0 and num > 1:
return 1
return 0
matrix = []
for y in range(rows):
row = [is_prime(y * cols + x) for x in range(cols)]
matrix.append(row)
return matrix
class FloodFill():
dict_x = {}
def eight_formation(self, x, y):
return (
(x - 1, y - 1),
(x - 1, y),
(x - 1, y + 1),
(x, y - 1),
(x, y + 1),
(x + 1, y - 1),
(x + 1, y),
(x + 1, y + 1),
)
def __init__(self, matrix):
self.matrix = matrix
def print_array(self):
for row in self.matrix:
for pixel in row:
print(pixel, end=" ")
print()
def recursive_list_based_8_floodfill(self, x=0, y=0, color=0, inputcolor=2):
if (
-1 < x < len(self.matrix[0])
and
-1 < y < len(self.matrix)
and self.matrix[y][x] == color
):
self.matrix[y][x] = inputcolor
neighbours = self.eight_formation(x, y)
for i, j in neighbours:
if not (i, j) in self.dict_x:
self.dict_x[(i, j)] = True
self.recursive_list_based_8_floodfill(i, j, color, inputcolor)
def get_inputs(rows=0, cols=0, x=0, y=0):
matrix = create_image(rows, cols)
ff = FloodFill(matrix)
print("x----Black and White Matrix Before----x")
ff.print_array()
print()
print("x----Matrix After Flood Filling Color 2----x")
ff.recursive_list_based_8_floodfill(x, y)
ff.print_array()
if __name__ == "__main__":
fire.Fire(get_inputs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment