Skip to content

Commit

Permalink
Utils/algo: faster grid neighbors bound checking
Browse files Browse the repository at this point in the history
  • Loading branch information
mebeim committed Dec 11, 2020
1 parent 036e08d commit c70fb6b
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions utils/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,21 @@ def _grid_neighbors(deltas):
'''
def g(grid, r, c, avoid='#'):
'''Get neighbors of a cell in a 2D grid (matrix) i.e. list of lists or
similar. Performs bounds checking.
similar. Performs bounds checking. Grid is assumed to be rectangular.
'''
width = len(grid)
height = len(grid[0])

for dr, dc in deltas:
rr, cc = (r + dr, c + dc)
if 0 <= rr < width and 0 <= cc < height:
maxr = len(grid) - 1
maxc = len(grid[0]) - 1
check = r == 0 or r == maxr or c == 0 or c == maxc

if check:
for dr, dc in deltas:
rr, cc = (r + dr, c + dc)
if 0 <= rr <= maxr and 0 <= cc <= maxc:
if grid[rr][cc] not in avoid:
yield (rr, cc)
else:
for dr, dc in deltas:
rr, cc = (r + dr, c + dc)
if grid[rr][cc] not in avoid:
yield (rr, cc)

Expand Down

0 comments on commit c70fb6b

Please sign in to comment.