Problem solution · Python

ABC387 D — Snaky Walk

ABC387 D — Snaky Walk: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Breadth-first search
Source
KATO-Hiro AtCoder Solutions
Length
69 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For ABC387 D — Snaky Walk, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 69 lines of Python from the credited upstream file abc387_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.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC387 D — Snaky Walk · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys    from collections import deque     input = sys.stdin.readline     h, w = map(int, input().split())    # TODO: Change input format if needs.    grid = [list(input().rstrip()) for _ in range(h)]    sy, sx = -1, -1    gy, gx = -1, -1     for i in range(h):        for j in range(w):            if grid[i][j] == "S":                sy, sx = i, j            elif grid[i][j] == "G":                gy, gx = i, j     inf = 10**18    ans = inf    dxy = [[(-1, 0), (1, 0)], [(0, -1), (0, 1)]]     for _ in range(2):        d = deque()        d.append((sy, sx))        pending = inf        dist = [[pending] * w for _ in range(h)]        dist[sy][sx] = 0  # Initialize         while d:            y, x = d.popleft()             if dist[y][x] == pending:                continue             # 現在のマスから次の移動方向を決める            flag = (y + x) % 2             for dx, dy in dxy[flag]:                nx = x + dx                ny = y + dy                 if nx < 0 or nx >= w or ny < 0 or ny >= h:                    continue                if grid[ny][nx] == "#":                    continue                if dist[ny][nx] != pending:                    continue                 dist[ny][nx] = dist[y][x] + 1  # Update ans                d.append((ny, nx))         ans = min(ans, dist[gy][gx])        # 進む方向を逆にする        dxy[0], dxy[1] = dxy[1], dxy[0]     if ans == inf:        ans = -1     print(ans)  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗