Skip to content

Commit 4dc3db2

Browse files
committed
feat(algs): add flood fill (steps buggy)
1 parent 5ab7b37 commit 4dc3db2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

algorithms/flood_fill.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Flood Fill
3+
4+
Jessica Yung
5+
Jan 2018
6+
"""
7+
import numpy as np
8+
9+
class FloodFill2D:
10+
11+
def __init__(self, grid_width, grid_height, visited=None):
12+
self.grid_width = grid_width
13+
self.grid_height = grid_height
14+
if visited is None:
15+
self.visited = np.zeros((grid_height, grid_width))
16+
else:
17+
self.visited = visited
18+
self.steps_taken = np.zeros((grid_height, grid_width))
19+
20+
21+
def flood_fill(self, x, y, steps=0):
22+
"""Basic flood fill algorithm that visits every cell in a 2D grid, where adjacent cells are defined as up to eight cells next to the current cell (can move diagonally).
23+
DFS-based implementation.
24+
"""
25+
print("Current cell: ", x, y)
26+
print("Steps taken at start", self.steps_taken)
27+
print("Visited at start: ", self.visited)
28+
print("Steps at start: ", steps)
29+
if x >= self.grid_width or y >= self.grid_height:
30+
return
31+
if x < 0 or y < 0:
32+
return
33+
if self.visited[y][x]:
34+
print("Already visited ", x, y)
35+
return
36+
37+
# Mark current cell as visited
38+
self.visited[y][x] = True
39+
self.steps_taken[y][x] = steps
40+
print("Visited ", x, y, "in ", steps, " steps")
41+
print(self.steps_taken)
42+
print("Visited is now")
43+
print(self.visited)
44+
45+
# Visit every neighbouring cell
46+
for cell in self.neighbour(x, y):
47+
self.flood_fill(cell[0], cell[1], steps+1)
48+
49+
def neighbour(self, x, y):
50+
neighbours = []
51+
for dx in [-1,0,1]:
52+
for dy in [-1,0,1]:
53+
neighbours.append([x + dx, y + dy])
54+
return neighbours
55+
56+
ff = FloodFill2D(4, 3)
57+
ff.flood_fill(1,2)
58+
print(ff.steps_taken)
59+

0 commit comments

Comments
 (0)