Advertisement
themoosemind

Untitled

Oct 3rd, 2013
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. def search():
  2.     path = [[' ' for el in line] for line in grid]
  3.     parents = [[' ' for el in line] for line in grid]
  4.     closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
  5.     closed[init[0]][init[1]] = 1
  6.  
  7.     x = init[0]
  8.     y = init[1]
  9.     g = 0
  10.  
  11.     open = [[g, x, y]]
  12.  
  13.     found = False  # flag that is set when search is complet
  14.     resign = False # flag set if we can't find expand
  15.  
  16.     while not found and not resign:
  17.         if len(open) == 0:
  18.             resign = True
  19.             return 'fail'
  20.         else:
  21.             open.sort()
  22.             open.reverse()
  23.             next = open.pop()
  24.             x = next[1]
  25.             y = next[2]
  26.             g = next[0]
  27.            
  28.             if x == goal[0] and y == goal[1]:
  29.                 found = True
  30.             else:
  31.                 for i in range(len(delta)):
  32.                     x2 = x + delta[i][0]
  33.                     y2 = y + delta[i][1]
  34.                     if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
  35.                         if closed[x2][y2] == 0 and grid[x2][y2] == 0:
  36.                             g2 = g + cost
  37.                             open.append([g2, x2, y2])
  38.                             parents[x2][y2] = [x, y]
  39.                             closed[x2][y2] = 1
  40.                            
  41.     # Get solution back
  42.     x, y = goal
  43.     path[x][y] = '*'
  44.     while x != init[0] or y != init[1]:
  45.         if parents[x][y][0] - x == -1:
  46.             path[parents[x][y][0]][parents[x][y][1]] = 'v'
  47.         elif parents[x][y][0] - x == 1:
  48.             path[parents[x][y][0]][parents[x][y][1]] = '<'
  49.         elif parents[x][y][1] - y == -1:
  50.             path[parents[x][y][0]][parents[x][y][1]] = '>'
  51.         elif parents[x][y][1] - y == 1:
  52.             path[parents[x][y][0]][parents[x][y][1]] = '^'
  53.         x, y = parents[x][y]
  54.    
  55.     return path
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement