1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import heapq def bfs(mp): n = len(mp[0]) init_pos = ((0, 0), (0, 1)) target_pos = ((n-1, n-2), (n-1, n-1)) Q = [(0, init_pos, 0)] vis = set() def inrange(xy, xy0, mp): n = len(mp[0]) x, y = xy x0, y0 = xy0 if not (0 <= x < n and 0 <= y < n and 0 <= x0 < n and 0 <= y0 < n): return False if mp[x][y] == 1 or mp[x0][y0] == 1: return False return True while Q: moves, cur_pos, cur_dir = heapq.heappop(Q) if (cur_pos, cur_dir) in vis: continue vis.add((cur_pos, cur_dir)) if cur_pos == target_pos: return moves (x, y), (x0, y0) = cur_pos if inrange((x, y+1), (x0, y0+1), mp) and (((x, y+1), (x0, y0+1)), cur_dir) not in vis: heapq.heappush(Q, (moves+1, ((x, y+1), (x0, y0+1)), cur_dir)) if inrange((x+1, y), (x0+1, y0), mp) and (((x+1, y), (x0+1, y0)), cur_dir) not in vis: heapq.heappush(Q, (moves+1, ((x+1, y), (x0+1, y0)), cur_dir)) if cur_dir == 0: if inrange((x+1, y), (x0+1, y0), mp) and (((x, y), (x+1, y)), 1) not in vis: heapq.heappush(Q, (moves+1, ((x, y), (x+1, y)), 1)) else: if inrange((x, y+1), (x0, y0+1), mp) and (((x, y), (x, y+1)), 0) not in vis: heapq.heappush(Q, (moves+1, ((x, y), (x, y+1)), 0)) return -1
class Solution: def minimumMoves(self, grid) -> int: return bfs(grid)
|