Advertisement
Guest User

PacMan - DFS

a guest
Nov 24th, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. def print_way(cell, p_x, p_y):
  2.     stack = []
  3.     while cell[0] != p_x or cell[1] != p_y:
  4.         stack += [cell]
  5.         cell = cell[2]
  6.     stack += [cell]
  7.     print len(stack) - 1
  8.     for x in stack[::-1]:
  9.         print x[0], x[1]
  10.  
  11.  
  12. def print_history(history):
  13.     print len(history)
  14.     for x in history:
  15.         print x[0], x[1]
  16.  
  17.  
  18. def process(rows, columns, cur_cell, food_x, food_y, grid, history):
  19.     history += [cur_cell]
  20.     grid[cur_cell[0]][cur_cell[1]] = '#'
  21.     if cur_cell[0] == food_x and cur_cell[1] == food_y:
  22.         return True
  23.  
  24.     global order
  25.     for dir in order:
  26.         next_cell = [cur_cell[0] + dir[0], cur_cell[1] + dir[1], cur_cell]
  27.         if grid[next_cell[0]][next_cell[1]] in ['%', '#']:
  28.             continue
  29.         dfs_result = process(rows, columns, next_cell, food_x, food_y, grid, history)
  30.         if dfs_result:
  31.             return True
  32.     return False
  33.  
  34.  
  35. def main():
  36.     [p_x, p_y] = [int(i) for i in raw_input().strip().split()]
  37.     [food_x, food_y] = [int(i) for i in raw_input().strip().split()]
  38.     [rows, columns] = [int(i) for i in raw_input().strip().split()]
  39.  
  40.     grid = []
  41.     for i in xrange(rows):
  42.         line = raw_input().strip()
  43.         line_elem = []
  44.         for x in line:
  45.             line_elem += [x]
  46.         grid += [line_elem]
  47.     history = []
  48.     cur_cell = [p_x, p_y]
  49.  
  50.     process(rows, columns, cur_cell, food_x, food_y, grid, history)
  51.     print_history(history)
  52.     print_way(history[-1], p_x, p_y)
  53.  
  54.  
  55. #order = [[0, 1], [1, 0], [-1, 0], [0, -1]]
  56. order = [[1, 0], [0, 1], [0, -1], [-1, 0]]
  57. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement