philRG

BFS Great Escape

Sep 24th, 2021 (edited)
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. def bfs_paths(player_id, forbidden_moves):
  2.     # debug(f'BFS player {player_id} - {len(forbidden_moves)} forbidden moves = {forbidden_moves}')
  3.     start_x, start_y, walls_left = players[player_id]
  4.     # queue = [(start_x, start_y, [], [])]
  5.     queue = deque([(start_x, start_y, [], [])])
  6.     nodes_count = 0
  7.     new_start = time.time()
  8.     while queue:
  9.         # x, y, path, visited_states = queue.pop(0)
  10.         x, y, path, visited_states = queue.popleft()
  11.         # la petite fourmi se deplace pour chercher son chemin
  12.         for (dx, dy), _dir in DIRECTIONS.items():
  13.             if (x, y, _dir) in forbidden_moves:
  14.                 continue
  15.             new_x, new_y = (x + dx, y + dy)
  16.             if 0 <= new_x < width and 0 <= new_y < height:
  17.                 # state = hash((new_x, new_y, _dir))
  18.                 state = (new_x, new_y)
  19.                 # debug(state)
  20.                 if state in visited_states:
  21.                     continue
  22.                 if (player_id == 0 and new_x == width - 1) or (player_id == 1 and new_x == 0) or (player_id == 2 and new_y == height - 1):
  23.                     debug(f'BFS player {player_id} - nodes_count = {nodes_count}')
  24.                     debug(f'remaining time after BFS player {player_id} = {round((time.time() - new_start) * 1000, 2)} ms')
  25.                     yield path + [_dir]
  26.                 else:
  27.                     node = (new_x, new_y, path + [_dir], visited_states + [state])
  28.                     # queue.append(node)
  29.                     queue.append(node)
  30.                     nodes_count += 1
  31.  
  32. def shortest_path(player_id, forbidden_moves):
  33.     try:
  34.         return next(bfs_paths(player_id, forbidden_moves))
  35.     except StopIteration:
  36.         return None
Add Comment
Please, Sign In to add comment