import sequtils,queues type Pos = tuple[x,y:int] proc getchar_unlocked():char {. importc:"getchar_unlocked",header: "" .} proc scan(): int = while true: let k = getchar_unlocked() if k < '0': return result = 10 * result + k.ord - '0'.ord let h = scan() let w = scan() var M = newSeqWith(w,newSeq[bool](h)) # R かどうか var s : Pos var g : Pos for y in 0.. 0: let (x,y,isKnight,diff) = q.dequeue() const D : seq[seq[Pos]] = @[ @[(1,1),(-1,-1),(1,-1),(-1,1)], @[(1,2),(2,1),(-1,-2),(-2,-1),(-1,2),(-2,1),(1,-2),(2,-1)], ] let nextDiff = diff + 1 for d in D[isKnight]: let nx = x + d[0] let ny = y + d[1] if nx < 0 or ny < 0 or nx >= w or ny >= h : continue if nx == g.x and ny == g.y : quit $nextDiff,0 let nextIsKnight = if M[nx][ny]: 1 - isKnight else: isKnight if DP[nx][ny][nextIsKnight] <= nextDiff: continue DP[nx][ny][nextIsKnight] = nextDiff q.enqueue((nx,ny,nextIsKnight,nextDiff)) echo -1