|
| 1 | +import sys |
| 2 | +from collections import deque |
| 3 | + |
| 4 | +read = lambda: sys.stdin.readline().rstrip() |
| 5 | + |
| 6 | + |
| 7 | +class Problem: |
| 8 | + def __init__(self): |
| 9 | + self.n, self.m = map(int, read().split()) |
| 10 | + self.matrix = [list(map(int, read())) for _ in range(self.n)] |
| 11 | + |
| 12 | + def solve(self) -> None: |
| 13 | + print(self.dijkstra()) |
| 14 | + |
| 15 | + def dijkstra(self) -> int: |
| 16 | + queue, visited = deque([((0, 0), 1, True)]), {(True, 0, 0)} |
| 17 | + |
| 18 | + while queue: |
| 19 | + (x, y), depth, can_break = queue.popleft() |
| 20 | + if (x, y) == (self.m - 1, self.n - 1): |
| 21 | + return depth |
| 22 | + |
| 23 | + for nx, ny in [(x + dx, y + dy) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]]: |
| 24 | + if not (0 <= nx < self.m and 0 <= ny < self.n): |
| 25 | + continue |
| 26 | + |
| 27 | + if self.matrix[ny][nx] == 0 and (can_break, nx, ny) not in visited: |
| 28 | + visited.add((can_break, nx, ny)) |
| 29 | + queue.append(((nx, ny), depth + 1, can_break)) |
| 30 | + |
| 31 | + if self.matrix[ny][nx] == 1 and can_break and (False, nx, ny) not in visited: |
| 32 | + visited.add((False, nx, ny)) |
| 33 | + queue.append(((nx, ny), depth + 1, False)) |
| 34 | + |
| 35 | + return -1 |
| 36 | + |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + Problem().solve() |
0 commit comments