Skip to content

Commit fbee996

Browse files
committed
feat(bfs): add bfs on a 2d grid
1 parent 095b9fc commit fbee996

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

algorithms/bfs.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Breadth-first Search on a 2D grid
3+
4+
Note: 'steps' indicates order of expansion, not distance from the source cell.
5+
6+
Jessica Yung
7+
Jan 2018
8+
"""
9+
import numpy as np
10+
from queue import Queue
11+
12+
class BFS2D:
13+
14+
def __init__(self, grid_width, grid_height, visited=None):
15+
self.grid_width = grid_width
16+
self.grid_height = grid_height
17+
if visited is None:
18+
self.visited = np.zeros((grid_height, grid_width))
19+
else:
20+
self.visited = visited
21+
self.steps_taken = np.zeros((grid_height, grid_width))
22+
self.queue = Queue()
23+
24+
25+
def bfs(self, x, y, steps=0):
26+
"""Breadth-First Search 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).
27+
"""
28+
if x >= self.grid_width or y >= self.grid_height:
29+
return
30+
if x < 0 or y < 0:
31+
return
32+
if self.visited[y][x]:
33+
return
34+
35+
# Mark current cell as visited
36+
self.queue.put([x,y])
37+
self.visited[y][x] = True
38+
self.steps_taken[y][x] = steps
39+
steps += 1
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+
while not self.queue.empty():
47+
node = self.queue.get()
48+
for cell in self.neighbour(node[0], node[1]):
49+
cellx = cell[0]
50+
celly = cell[1]
51+
# print(cell)
52+
if cellx < 0 or cellx >= self.grid_width:
53+
continue
54+
if celly < 0 or celly >= self.grid_height:
55+
continue
56+
if not self.visited[cell[1], cell[0]]:
57+
self.queue.put(cell)
58+
self.visited[cell[1], cell[0]] = True
59+
self.steps_taken[celly, cellx] = steps
60+
steps += 1
61+
62+
def neighbour(self, x, y):
63+
neighbours = []
64+
for dx in [-1,0,1]:
65+
for dy in [-1,0,1]:
66+
neighbours.append([x + dx, y + dy])
67+
return neighbours
68+
69+
bfs = BFS2D(4, 3)
70+
bfs.bfs(1,2)
71+
print(bfs.steps_taken)
72+

0 commit comments

Comments
 (0)