Problem solution · Python

ABC453 D — Go Straight

ABC453 D — Go Straight: 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
92 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 ABC453 D — Go Straight, 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

  • 92 lines of Python from the credited upstream file abc453_d.py.
  • The implementation visibly relies on sequence storage, hash lookup, 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 codeABC453 D — Go Straight · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  # See# https://atcoder.jp/contests/abc450/submissions/74271594def encode(hi, wj, w):    return hi * w + wj  def decode(n, w):    return divmod(n, w)  def main():    import sys    from collections import deque, defaultdict     input = sys.stdin.readline     h, w = map(int, input().split())    s = [list(input().rstrip()) for _ in range(h)]    dxy = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)]    dxy = dxy[:4]    pending = -1    sy, sx, gy, gx = pending, pending, pending, pending     for i in range(h):        for j in range(w):            if s[i][j] == "S":                sy, sx = i, j            if s[i][j] == "G":                gy, gx = i, j     q = deque()    prev = [[pending for _ in range(4)] for _ in range(h * w)]    done = 10**6     def push(cur_y, cur_x, di, prev_d):        cur_pos = encode(cur_y, cur_x, w)         if prev[cur_pos][di] != pending:            return         prev[cur_pos][di] = prev_d        q.append((cur_pos, di))     for i in range(4):        push(sy, sx, i, done)     while q:        pos, dir = q.popleft()        y, x = decode(pos, w)         if (y, x) == (gy, gx):            print("Yes")            ans = []             while prev[pos][dir] != done:                ans.append("LRUD"[dir])                prev_dir = prev[pos][dir]                 y -= dxy[dir][1]                x -= dxy[dir][0]                pos = encode(y, x, w)                dir = prev_dir             print("".join(ans[::-1]))            exit()         for j, (dx, dy) in enumerate(dxy):            if s[y][x] == "o" and j != dir:                continue            if s[y][x] == "x" and j == dir:                continue             ny, nx = y + dy, x + dx             if not (0 <= ny < h):                continue            if not (0 <= nx < w):                continue            if s[ny][nx] == "#":                continue             push(ny, nx, j, dir)     print("No")  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 ↗