Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Lee's shortest path solution in Clear category for Open Labyrinth by kryksyh
#Finds shortest path using Lee (wave) algorithm
dirs = [(0, -1, 'S'), (0, 1, 'N'), (-1, 0, 'E'), (1, 0, 'W')]
def checkio(maze_map):
#init wave map
wave = [[90 * maze_map[x][y] for x in range(12)] for y in range(12)]
wave[1][1] = 1
# 10 * 10 iterations should be enough
for z in range(100):
for x in range(1, 11):
for y in range(1, 11):
#no need to recalc if been there already or wall
if wave[x][y]>0:
continue
#find neighbors that already been calculated ( not 0)
neighbors = [x for x in [wave[x + d[0]][y + d[1]] for d in dirs] if 0 < x < 90]
if len(neighbors):
minVal = min(neighbors)
wave[x][y] = minVal+1
path = ''
pos = (10, 10)
#finding shortes path, going backword to start
while pos != (1, 1):
# neighbor = (wave value, [x,y], direction: NSEW)
neighbors = [(wave[pos[0] + d[0]][pos[1] + d[1]], (d[0], d[1]), d[2]) for d in dirs]
m = min(neighbors)
path += m[2]
pos = (pos[0] + m[1][0], pos[1] + m[1][1])
#since path is from end to start, should reverse it
return ''.join(reversed(path))
if __name__ == '__main__':
#This code using only for self-checking and not necessary for auto-testing
def check_route(func, labyrinth):
MOVE = {"S": (1, 0), "N": (-1, 0), "W": (0, -1), "E": (0, 1)}
#copy maze
route = func([row[:] for row in labyrinth])
pos = (1, 1)
goal = (10, 10)
for i, d in enumerate(route):
move = MOVE.get(d, None)
if not move:
print("Wrong symbol in route")
return False
pos = pos[0] + move[0], pos[1] + move[1]
if pos == goal:
return True
if labyrinth[pos[0]][pos[1]] == 1:
print("Player in the pit")
return False
print("Player did not reach exit")
return False
# These assert are using only for self-testing as examples.
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 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0, 0, 0, 0, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Need left maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "The big dead end."
print("The local tests are done.")
April 19, 2015
Comments: