I'm currently writing a short code as follows that returns the co-ordinates and size of the longest path in a grid with the following constraints:
- Only move up,down,left,right
- Only move to a cell that has a maximum difference of 1
- Cannot pass through a cell twice
- Must start in the top row
My code is as follows:
import numpy as np
grid = np.random.randint(3, size=(5, 5))
def get_longest_path(grid):
# setup
cols, rows = grid.shape # length, width
# pathfinder function
def pathfinder(i,j):
best, best_path = 0, []
udlr = {(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)} # up down left right directions
for x, y in udlr:
if 0 <= x < cols and 0 <= y < rows and abs(grid[x][y] - grid[i][j]) <= 1: # check it's in bounds
#grid[x][y] > grid[i][j]
n, path = pathfinder(x,y)
if n > best:
best, best_path = n, path
return best + 1, [(i,j)] + best_path
#return longest path
return max(pathfinder(0,j) for j in range(rows))
get_longest_path(grid)
As far as I can tell, it works fine if I use the constraint grid[x][y] > grid[i][j]
in place of abs(grid[x][y] - grid[i][j]) <= 1
. However, if I run this as it is, the Jupyter kernel dies straight away.
Perhaps it starts an infinite loop, but I can't see why this would be the case.
Any advice would be appreciated, thank you.