Approach
Breadth-first search
For ABC394 E — Palindromic Shortest Path, 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
- 67 lines of Python from the credited upstream file abc394_e.py.
- The implementation visibly relies on sequence storage, 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 n = int(input())11 c = [list(input().rstrip()) for _ in range(n)]12 inf = 10**913 dist = [[inf] * n for _ in range(n)]14 q = deque()15 16 def push(i, j, d):17 if dist[i][j] != inf:18 return19 20 dist[i][j] = d21 q.append((i, j))22 23 24 25 26 for i in range(n):27 push(i, i, 0)28 29 for i in range(n):30 for j in range(n):31 if c[i][j] == "-":32 continue33 34 push(i, j, 1)35 36 while q:37 s, t = q.popleft()38 39 40 for ns in range(n):41 for nt in range(n):42 if c[ns][s] == "-":43 continue44 if c[t][nt] == "-":45 continue46 if c[ns][s] != c[t][nt]:47 continue48 49 push(ns, nt, dist[s][t] + 2)50 51 for i in range(n):52 ans = list()53 54 for j in range(n):55 d = dist[i][j]56 57 if d == inf:58 d = -159 60 ans.append(d)61 62 print(*ans)63 64 65if __name__ == "__main__":66 main()67