Skip to content

Instantly share code, notes, and snippets.

@serser
Last active December 6, 2017 03:34
Show Gist options
  • Save serser/b9d99b5c7f9aed85330d0944b0383c8e to your computer and use it in GitHub Desktop.
Save serser/b9d99b5c7f9aed85330d0944b0383c8e to your computer and use it in GitHub Desktop.
print out maze path
# -----------
# User Instructions:
#
# Modify the the search function so that it returns
# a shortest path as follows:
#
# [['>', 'v', ' ', ' ', ' ', ' '],
# [' ', '>', '>', '>', '>', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', '*']]
#
# Where '>', '<', '^', and 'v' refer to right, left,
# up, and down motions. Note that the 'v' should be
# lowercase. '*' should mark the goal cell.
#
# You may assume that all test cases for this function
# will have a path from init to goal.
# ----------
grid = [[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
def search(grid,init,goal,cost):
# ----------------------------------------
# modify code below
# ----------------------------------------
closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
closed[init[0]][init[1]] = 1
expand = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
x = init[0]
y = init[1]
g = 0
open = [[g, x, y]]
paths = [] #keeps list of actions and current block
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
while not found and not resign:
if len(open) == 0:
resign = True
return 'fail'
else:
open.sort()
open.reverse()
next = open.pop()
x = next[1]
y = next[2]
g = next[0]
if x == goal[0] and y == goal[1]:
expand[x][y] = '*'
found = True
else:
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
#print 'next',x2,y2
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
open.append([g2, x2, y2])
closed[x2][y2] = 1
if x==0 and y==0:
#print 'initial status'
paths.append([(x2,y2), [delta_name[i]]])
else:
for j,p in enumerate(paths):
(px,py),pl = p
pl_copy = pl[:]
if (x==px) & (y==py):
pl_copy.append(delta_name[i])
paths.append([(x2,y2), pl_copy])
for p in paths:
(px,py), pl = p
if (px == goal[0]) & (py == goal[1]):
optimal_path = pl
#print 'optimal,length',optimal_path, len(optimal_path)
break
x0,y0=init
for action in optimal_path:
expand[x0][y0] = action
idx = delta_name.index(action)
dx,dy = delta[idx]
x0 += dx
y0 += dy
return expand # make sure you return the shortest path
print search(grid,init,goal,cost)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment