Advertisement
_cronos2

HR 101 Feb #3

Mar 1st, 2014
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. # Enter your code here. Read input from STDIN. Print output to STDOUT
  2.  
  3. T = input()
  4.  
  5. DOWN = 1
  6. RIGHT = 1j
  7. UP, LEFT = -DOWN, -RIGHT
  8.  
  9.  
  10. def add(x, y):
  11.     return x[0] + y[0], x[1] + y[1]
  12.  
  13. def find_coords(forest, N, M):
  14.    
  15.     she, exit = 'M', '*'
  16.    
  17.     she_pos, exit_pos = False, False
  18.    
  19.     for row in xrange(N):
  20.         if not she_pos:
  21.             col = forest[row].find(she)
  22.             if col > -1:
  23.                 she_pos = row, col
  24.            
  25.         if not exit_pos:
  26.             col = forest[row].find(exit)
  27.             if col > -1:
  28.                 exit_pos = row, col
  29.    
  30.     return she_pos, exit_pos
  31.    
  32.  
  33. def imag_coords(z):
  34.     return int(z.real), int(z.imag)
  35.  
  36.  
  37. def get_cell(forest, coords, N, M):
  38.    
  39.     i, j = coords
  40.    
  41.     return (0 <= i < N and 0 <= j < M and forest[i][j]) or 'X'
  42.  
  43.  
  44. def is_correct(forest, she, exit, K, _from = None):
  45.     if she == exit and K == 0:
  46.         return True
  47.     elif K < 0:
  48.         return False
  49.    
  50.     paths = possible_paths(forest, she, _from)
  51.     length = len(paths)
  52.    
  53.     #print she, K, _from, paths
  54.    
  55.     if length == 0:  # no exit
  56.         return False
  57.     elif length == 1:
  58.         return is_correct(forest, add(she, imag_coords(paths[0][0])), exit, K, paths[0][1])
  59.     else:
  60.         res = False
  61.        
  62.         for path in paths:
  63.             res = res or is_correct(forest, add(she, imag_coords(path[0])), exit, K - 1, path[1])
  64.        
  65.         return res
  66.  
  67.    
  68. def possible_paths(forest, she, _from):
  69.    
  70.     TREE = 'X'
  71.     valid = lambda cell: get_cell(forest, cell, N, M) != TREE
  72.    
  73.     dirs = [LEFT, RIGHT, UP, DOWN]
  74.    
  75.     possible = [(dir, -dir) for dir in dirs if valid(add(she, imag_coords(dir))) and dir != _from]
  76.    
  77.     return possible
  78.    
  79.  
  80. def solution(forest, she, exit, K):
  81.    
  82.     OK, FAIL = 'Impressed', 'Oops!'
  83.    
  84.     return OK if is_correct(forest, she, exit, K) else FAIL
  85.    
  86.  
  87.  
  88. for t in xrange(T):
  89.    
  90.     N, M = (int(x) for x in raw_input().split())
  91.    
  92.     forest = [raw_input() for i in xrange(N)]
  93.    
  94.     K = input()
  95.    
  96.     she, exit = find_coords(forest, N, M)
  97.    
  98.     print solution(forest, she, exit, K)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement