So a little context to understand the code:
- This is a helper function to solve a bigger problem here
- Quick summary: A Knight is in a dungeon/2D grid of Ints, starts at 0,0 and must reach the last cell at the bottom right to find the princess
- The purpose of this helper function is to return all neighbors of a given starting point, given some constraints:
- The knight's starting point is always upper-left - 0,0
- The knight can only travel right or down, 1 cell at a time
- The target / base case is bottom right of the grid/dungeon where the princess is
Code below
def get_neighbors(d, x, y, coll):
# d == abbr. for dungeon is our board
# For example:
#[-8, -13, -8]
#[-24, 28, 28]
#[-13, -13, -30]
# coll == abbr. for collection, how I keep track of all returned neighbors
# We start our knight in the upper left hand corner
row_length = len(d)
col_length = len(d[0])
if (x,y) == (row_length - 1, col_length - 1): # Once we reach the bottom right corner we are done
return coll
for dx in range(0, 2):
for dy in range(0, 2):
if dx == 0 and dy == 0 or dx == 1 and dy == 1: # If cell is not to the bottom or to the right, skip it
continue
if x + dx > len(d[x]) - 1 or y + dy > len(d) - 1: # Out of bounds check
continue
neighbor = (x + dx, y + dy)
# I'm wondering why I even need this line, if I am only going to the right and to the bottom each time
# Why do I need to guard against duplicates
if neighbor not in coll:
coll.append(neighbor)
get_neighbors(d, x + dx, y + dy, coll)
return coll
Is there anything I should do differently?