E - 迷子の子猫たち / Lost Kittens Editorial by admin Editorial for printing
GPT 5.2 HighOverview
Starting from @, collect all kittens F, and find the minimum number of steps to finally reach the goal G (or -1 if impossible).
Key Observations
- The condition that “kittens move with you once rescued” does not affect the movement cost (1 step) itself.
Ultimately, what we need to do is find the shortest path that “starts from@, visits allFs, and finally goes toG.” - However, the grid can be as large as \(200 \times 200\), and the number of kittens \(K \le 10\), so:
- A BFS on the grid with states as “position + collected set” (state count \(H \cdot W \cdot 2^K\)) is theoretically possible but can be heavy in some cases.
- Also, “brute-forcing the order of kittens (\(K!\))” gives \(10! = 3{,}628{,}800\) permutations, which is impractical when including distance computation for each order.
- The key insight is that we can split this into two stages:
- Shortest distances on the grid can be computed with BFS (we can’t use Manhattan distance due to obstacles
#). - The optimal visiting order can be solved with “TSP bit DP” in \(O(K^2 2^K)\) (which is fast enough for \(K \le 10\)).
- Shortest distances on the grid can be computed with BFS (we can’t use Manhattan distance due to obstacles
Algorithm
Enumerate important points
- \(0\): Start
@ - \(1..K\): Kittens
F(\(K\) of them) - The goal
Gis treated separately since we “just go there at the end”; we only store its distances.
- \(0\): Start
Precompute distances with BFS
For each important point (start and each kitten, \(K+1\) total), run BFS to compute:- Shortest distances between important points:
dist_nodes[i][j] - Shortest distance from each point to the goal:
goal_dist[i]
- Shortest distances between important points:
If unreachable, the distance is treated as infinity (INF in the code).
- Find the shortest distance to collect all kittens using bit DP (TSP)
Definedp[mask][i]as follows:mask: the set of collected kittens (\(K\) bits)i: the index of the last kitten visited (\(0..K-1\))- Value: “the minimum number of steps starting from the start, having collected all kittens in
mask, with the last one being kitteni”
The transition is:
- For a kitten j not yet collected, collect it next:
\(dp[mask \cup \{j\}][j] = \min(dp[mask][i] + dist(F_i, F_j))\)
(Skip edges that are unreachable.)
- Finally, go to the goal
For the full collectionfull = (1<<K)-1:- The answer is the minimum of \(dp[full][i] + dist(F_i, G)\).
- If none are achievable, output
-1.
Complexity
- Time complexity:
BFS is run \(K+1\) times, so \(O((K+1)HW)\); bit DP is \(O(K^2 2^K)\).
Overall: \(O((K+1)HW + K^2 2^K)\) - Space complexity:
BFS distance array is \(O(HW)\) (reused for each BFS),
precomputed distances are \(O(K^2)\), DP is \(O(K 2^K)\).
Overall: \(O(HW + K2^K)\)
Implementation Notes
Using
-1(unvisited) in BFS and only reflecting reachable distances in the distance table makes things easier to handle.If
dist_nodes/goal_distisINF, exclude it from transitions and candidates; otherwise, you may incorrectly use unreachable paths.Be careful about the offset between kitten DP indices and
points(where@is 0 and kittens are 1..K); in the code, kittenicorresponds to pointi+1.Source Code
import sys
from collections import deque
def bfs(grid, H, W, sr, sc):
dist = [[-1] * W for _ in range(H)]
dist[sr][sc] = 0
q = deque([(sr, sc)])
while q:
r, c = q.popleft()
nd = dist[r][c] + 1
nr = r - 1
if nr >= 0 and grid[nr][c] != '#' and dist[nr][c] == -1:
dist[nr][c] = nd
q.append((nr, c))
nr = r + 1
if nr < H and grid[nr][c] != '#' and dist[nr][c] == -1:
dist[nr][c] = nd
q.append((nr, c))
nc = c - 1
if nc >= 0 and grid[r][nc] != '#' and dist[r][nc] == -1:
dist[r][nc] = nd
q.append((r, nc))
nc = c + 1
if nc < W and grid[r][nc] != '#' and dist[r][nc] == -1:
dist[r][nc] = nd
q.append((r, nc))
return dist
def main():
input = sys.stdin.readline
H, W, K = map(int, input().split())
grid = [list(input().rstrip('\n')) for _ in range(H)]
start = None
goal = None
cats = []
for r in range(H):
for c in range(W):
ch = grid[r][c]
if ch == '@':
start = (r, c)
elif ch == 'G':
goal = (r, c)
elif ch == 'F':
cats.append((r, c))
INF = 10**18
points = [start] + cats # indices: 0=start, 1..K=cats
M = K + 1
dist_nodes = [[INF] * M for _ in range(M)]
goal_dist = [INF] * M
gr, gc = goal
for i in range(M):
sr, sc = points[i]
dist = bfs(grid, H, W, sr, sc)
goal_d = dist[gr][gc]
if goal_d != -1:
goal_dist[i] = goal_d
for j in range(M):
tr, tc = points[j]
d = dist[tr][tc]
if d != -1:
dist_nodes[i][j] = d
if K == 0:
ans = goal_dist[0]
print(-1 if ans >= INF else ans)
return
dp = [[INF] * K for _ in range(1 << K)]
for i in range(K):
d = dist_nodes[0][i + 1]
if d < INF:
dp[1 << i][i] = d
for mask in range(1 << K):
for i in range(K):
cur = dp[mask][i]
if cur >= INF:
continue
for j in range(K):
if (mask >> j) & 1:
continue
nd = dist_nodes[i + 1][j + 1]
if nd >= INF:
continue
nmask = mask | (1 << j)
val = cur + nd
if val < dp[nmask][j]:
dp[nmask][j] = val
full = (1 << K) - 1
ans = INF
for i in range(K):
cur = dp[full][i]
if cur >= INF:
continue
dg = goal_dist[i + 1]
if dg >= INF:
continue
ans = min(ans, cur + dg)
print(-1 if ans >= INF else ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
posted:
last update: