Approach
Breadth-first search
For ABC405 D — Escape Route, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 69 lines of Python from the credited upstream file abc405_d.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def main():5 import sys6 from collections import deque7 8 input = sys.stdin.readline9 10 h, w = map(int, input().split())11 12 grid = [list(input().rstrip()) for _ in range(h)]13 d = deque()14 pending = -115 dist = [[pending] * w for _ in range(h)]16 17 for i in range(h):18 for j in range(w):19 if grid[i][j] == "E":20 d.append((i, j))21 dist[i][j] = 0 22 23 visited = [[False] * w for _ in range(h)]24 dxy = [(-1, 0), (1, 0), (0, -1), (0, 1)]25 26 while d:27 y, x = d.popleft()28 29 if dist[y][x] == pending:30 continue31 32 if visited[y][x]:33 continue34 35 visited[y][x] = True36 37 for dx, dy in dxy:38 nx = x + dx39 ny = y + dy40 41 if nx < 0 or nx >= w or ny < 0 or ny >= h:42 continue43 if visited[ny][nx]:44 continue45 if grid[ny][nx] == "#":46 continue47 if dist[ny][nx] != pending and dist[ny][nx] <= dist[y][x]:48 continue49 50 if dy == 1:51 grid[ny][nx] = "^"52 elif dy == -1:53 grid[ny][nx] = "v"54 elif dx == 1:55 grid[ny][nx] = "<"56 elif dx == -1:57 grid[ny][nx] = ">"58 59 dist[ny][nx] = dist[y][x] + 1 60 d.append((ny, nx))61 62 for i in range(h):63 ans = "".join(grid[i])64 print(ans)65 66 67if __name__ == "__main__":68 main()69