I like the idea of a series. I suppose this is a nice-enough warm up to Djiskstra.
def neighbors(maze, i, j):
toTry = []
if i > 0:
toTry.append((i-1, j))
if j > 0:
toTry.append((i, j-1))
if i + 1 < len(maze):
toTry.append((i+1, j))
if j + 1 < len(maze[i]):
toTry.append((i, j+1))
final = [(a, b) for (a, b) in toTry if maze[a][b] == '.']
return final
def path_finder(maze):
maze = maze.split()
for row in maze:
assert(len(row) == len(maze))
cost = {}
toVisit = set([(0,0)])
cost[(0,0)] = 0
target = (len(maze)-1, len(maze)-1)
while toVisit:
i, j = toVisit.pop()
c = cost[(i, j)] + 1
for (a, b) in neighbors(maze, i, j):
if (a, b) not in cost:
cost[(a, b)] = c
toVisit.add((a, b))
elif cost[(a, b)] > c:
cost[(a, b)] = c
toVisit.add((a, b))
if target in cost:
return cost[target]
return False