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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: n = len(grid) if grid[0][0] == 1: return -1 q = [(0, 0)] step = [1] f = {} for i in range(n): for j in range(n): f[(i, j)] = False f[(0, 0)] = True while (n - 1, n - 1) not in q: if len(q) == 0: return -1 x, y = q[0] cur_step = step[0] if x + 1 < n: if y + 1 < n and grid[x + 1][y + 1] == 0 and not f[(x + 1, y + 1)]: q.append((x + 1, y + 1)) step.append(cur_step + 1) f[(x + 1, y + 1)] = True if grid[x + 1][y] == 0 and not f[(x + 1, y)]: q.append((x + 1, y)) step.append(cur_step + 1) f[(x + 1, y)] = True if y - 1 >= 0 and grid[x + 1][y - 1] == 0 and not f[(x + 1, y - 1)]: q.append((x + 1, y - 1)) step.append(cur_step + 1) f[(x + 1, y - 1)] = True if x - 1 >= 0: if y + 1 < n and grid[x - 1][y + 1] == 0 and not f[(x - 1, y + 1)]: q.append((x - 1, y + 1)) step.append(cur_step + 1) f[(x - 1, y + 1)] = True if grid[x - 1][y] == 0 and not f[(x - 1, y)]: q.append((x - 1, y)) step.append(cur_step + 1) f[(x - 1, y)] = True if y - 1 >= 0 and grid[x - 1][y - 1] == 0 and not f[(x - 1, y - 1)]: q.append((x - 1, y - 1)) step.append(cur_step + 1) f[(x - 1, y - 1)] = True if y + 1 < n and grid[x][y + 1] == 0 and not f[(x, y + 1)]: q.append((x, y + 1)) step.append(cur_step + 1) f[(x, y + 1)] = True if y - 1 >= 0 and grid[x][y - 1] == 0 and not f[(x, y - 1)]: q.append((x, y - 1)) step.append(cur_step + 1) f[(x, y - 1)] = True q = q[1:] step = step[1:] return step[q.index((n - 1, n - 1))]
|