Approach
Breadth-first search
For ABC339 D — Synchronized Players , 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
- 104 lines of Python from the credited upstream file abc339_d.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 s = [list(input().rstrip()) for _ in range(n)]12 pos = []13 14 for i in range(n):15 for j in range(n):16 if s[i][j] == "P":17 pos.append((i, j))18 19 20 21 22 23 def to_hash(pos):24 p00, p01 = pos[0]25 p10, p11 = pos[1]26 27 value = p0028 value = value * n + p0129 value = value * n + p1030 value = value * n + p1131 32 return value33 34 def to_pos(hash):35 36 p11 = hash % n37 hash = n38 p10 = hash % n39 hash = n40 41 p01 = hash % n42 hash = n43 p00 = hash % n44 hash = n45 46 pos = [(p00, p01), (p10, p11)]47 48 return pos49 50 n4 = n**451 inf = 10**952 53 dist = [inf] * n454 id = to_hash(pos)55 dist[id] = 056 57 q = deque([id])58 dxy = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)]59 dxy = dxy[:4]60 61 while q:62 cur_id = q.popleft()63 pos = to_pos(cur_id)64 d = dist[cur_id]65 66 67 for dx, dy in dxy:68 npos = []69 70 for y, x in pos:71 nx = x + dx72 ny = y + dy73 74 75 if nx < 0 or nx >= n or ny < 0 or ny >= n or s[ny][nx] == "#":76 nx, ny = x, y77 78 npos.append((ny, nx))79 80 nid = to_hash(npos)81 82 if dist[nid] != inf:83 continue84 85 dist[nid] = d + 186 q.append(nid)87 88 ans = inf89 90 for id, di in enumerate(dist):91 pos = to_pos(id)92 93 if pos[0] == pos[1]:94 ans = min(ans, di)95 96 if ans == inf:97 ans = -198 99 print(ans)100 101 102if __name__ == "__main__":103 main()104