Problem:


Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1



Sample input:
3 5 2
3 2 3 4
.....
.@..@
..@..


Sample output:
5

Submission status: Accepted

Solution code:
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    from collections import deque
    
    H,W,K=MI()
    x1,y1,x2,y2=MI()
    
    C=[]
    C.append(["@"]*(W+2))
    for _ in range(H):
        c=["@"] + list(input()) + ["@"]
        C.append(c)
    C.append(["@"]*(W+2))
    
    # 各ますにつき4方向分のデータを持つ，コストは（移動回数，今直線で動いた数）でもつ，移動回数がより重要視される
    inf=10**10
    D=[[[(inf,inf)]*4 for _ in range(W+2)]for _ in range(H+2)]#下上右左の4方向
    # D[i][j][k]はi行j列k向き
    
    
    dq=deque()
    for k in range(4):
        D[x1][y1][k]=(0,0)
        dq.append((x1,y1,k,0,0))
    
    dx=[1,-1,0,0]
    dy=[0,0,-1,1]
    
    
    #01BFSでいけそう
    
    while len(dq):
        x,y,d,cnt,k=dq.popleft()
        
        for nd in range(4):
            #方向そのまま
            if nd==d:
                nx=x+dx[nd]
                ny=y+dy[nd]
                nk=(k+1)%K
                ncnt=cnt
                if k+1>=K:
                    ncnt+=1
            #方向転換
            else:
                nk=0
                ncnt=cnt
                if k!=0:
                    ncnt+=1
                nx=x
                ny=y
            if C[nx][ny]==".":
                if D[nx][ny][nd] > (ncnt,nk):#更新する場合だけ
                    D[nx][ny][nd]=(ncnt,nk)
                    if ncnt==cnt:
                        dq.appendleft((nx,ny,nd,ncnt,nk))
                    else:
                        dq.append((nx,ny,nd,ncnt,nk))
                    
    ans=inf
    for d in range(4):
        temp=D[x2][y2][d][0]
        if D[x2][y2][d][1]:
            temp+=1
        ans=min(ans,temp)
        
    if ans>=inf:
        ans=-1
    print(ans)
    
    
    
    # for i in range(1,H+1):
    #     for j in range(1,W+1):
    #         print(D[i][j])
    
    
    
    
    
        
    
                    
            

main()

Submission status: Accepted

Solution code:
from collections import deque


H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split())
grid = [input() for _ in range(H)]

INF = float('inf')
path = [[[(INF, INF)] * 4 for _ in range(W)] for _ in range(H)] #3次元配列。各方向に対して(コスト、連続移動ます)のtapleを持つ

D = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 上:0, 右:1, 下:2, 左:3

# 初期処理
q = deque() #探索しているところをここに加えていくんだと思う。
for d in range(4):
    path[x1][y1][d] = (1, 0)  # スタート地点では(1, 0)
    q.append((x1, y1, d, 1, 0)) # (x, y, 進行方向[d], 移動回数[c], 進行済マス数[k])

# 01BFS
while q:
    x, y, d, c, k = q.popleft()

    # nx, ny: 次の座標
    # nd: 次の進行方向
    # nc: 次の移動回数
    # nk: 次の進行済マス数
    for nd in range(4):
        if nd == d:
            dx, dy = D[nd]
            nk = 1 if k == K else k + 1
            nc = c + 1 if k == K else c
        else:
            dx, dy = 0, 0
            nk = 0
            nc = c + 1
        nx = x + dx; ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == '.' and path[nx][ny][nd] > (nc, nk):
            path[nx][ny][nd] = (nc, nk)
            if nc == c:
                q.appendleft((nx, ny, nd, nc, nk))
            else:
                q.append((nx, ny, nd, nc, nk))

# ゴール地点の最小コストを求める
ans = INF
for d in range(4):
    ans = min(ans, path[x2][y2][d][0])
ans = -1 if ans == INF else ans
print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

H, W, K = mapint()
y1, x1, y2, x2 = mapint()
pond = [list(input()) for _ in range(H)]
from collections import deque
Q = deque([(y1-1, x1-1)])

inf = 10**18
dist = [[inf]*W for _ in range(H)]
dist[y1-1][x1-1] = 0
while Q:
    y, x = Q.popleft()
    if y==y2-1 and x==x2-1:
        break
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        for i in range(1, K+1):
            ny, nx = y+dy*i, x+dx*i
            if ny<0 or ny>=H or nx<0 or nx>=W:
                break
            if pond[ny][nx]=='@':
                break
            if dist[ny][nx]<=dist[y][x]:
                break
            if dist[ny][nx]>dist[y][x]+1:
                dist[ny][nx] = dist[y][x]+1
                Q.append((ny, nx))
if dist[y2-1][x2-1]>=10**17:
    print(-1)
else:
    print(dist[y2-1][x2-1])

Submission status: Accepted

Solution code:
import collections

H, W, K = [int(x) for x in input().split()]
X1, Y1, X2, Y2 = [int(x) for x in input().split()]
C = [input().strip() for _ in range(H)]

ans = [[float("inf")] * W for j in range(H)]

q = collections.deque()
q.append((X1 - 1, Y1 - 1))

ans[X1 - 1][Y1 - 1] = 0

while q:
    cx, cy = q.popleft()
    cc = ans[cx][cy]
    nc = cc + 1

    # right
    for i in range(1, K + 1):
        if cy + i >= W or C[cx][cy + i] == "@":
            break
        if ans[cx][cy + i] <= nc - 1:
            break
        if ans[cx][cy + i] <= nc:
            continue
        ans[cx][cy + i] = nc
        q.append((cx, cy + i))
    # left
    for i in range(1, K + 1):
        if cy - i <= -1 or C[cx][cy - i] == "@":
            break
        if ans[cx][cy - i] <= nc - 1:
            break
        if ans[cx][cy - i] <= nc:
            continue
        ans[cx][cy - i] = nc
        q.append((cx, cy - i))
    # up
    for i in range(1, K + 1):
        if cx - i <= -1 or C[cx - i][cy] == "@":
            break
        if ans[cx - i][cy] <= nc - 1:
            break
        if ans[cx - i][cy] <= nc:
            continue
        ans[cx - i][cy] = nc
        q.append((cx - i, cy))
    # down
    for i in range(1, K + 1):
        if cx + i >= H or C[cx + i][cy] == "@":
            break
        if ans[cx + i][cy] <= nc - 1:
            break
        if ans[cx + i][cy] <= nc:
            continue
        ans[cx + i][cy] = nc
        q.append((cx + i, cy))

if ans[X2 - 1][Y2 - 1] == float("inf"):
    print(-1)
else:
    print(ans[X2 - 1][Y2 - 1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque

def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = [input() for _ in range(H)]

    adj = [[] for _ in range(W*H)]
    dx = [1,-1,0,0]
    dy = [0,0,1,-1]
    INF = 10**12
    
    for i in range(H):
        for j in range(W):
            if c[i][j] == '@': continue
            for k in range(4):
                y = i + dy[k]
                x = j + dx[k]
                if 0 <= y < H and 0 <= x < W and c[y][x] == '.':
                    adj[W*i+j].append(W*y+x)
    
    queue = deque([W*x1+y1])
    visit = [INF] * (W*H)
    visit[W*x1+y1] = 0
    
    while queue:
        now = queue.popleft()
        for u in adj[now]:
            # nowからuの方向に'.'が続くかぎり（最大K個）
            count = 0
            direct = u - now
            fromC = now
            toC = u
            while count < K and toC in adj[fromC] and visit[now] < visit[toC]:
                count += 1
                if visit[toC] == INF:
                    queue.append(toC)
                    visit[toC] = visit[now] + 1
                fromC = toC
                toC += direct 

    print(visit[W*x2+y2]) if visit[W*x2+y2] < INF else print(-1)
    # print(visit)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  for i in range(4):
    tx,ty = nx,ny
    step = K
    while step > 0:
      tx += dxdy[i][0]
      ty += dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      if reach[nx][ny] + 1 == reach[tx][ty]:
        #同じときはQに加える必要はないが、そのまま先に進んだら得の場合があるのでContinue
        step -=1
        continue
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
      step -=1

#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      if reach[nx][ny] + 1 == reach[tx][ty]:
        #同じときはQに加える必要はないが、そのまま先に進んだら得の場合があるのでContinue
        continue
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))

#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Accepted

Solution code:
h,w,k=map(int,input().split())

y1,x1,y2,x2=map(int,input().split())

maze=[list(input()) for _ in range(h)]

from collections import deque
stack=deque([(y1-1,x1-1)])

before=[[0]*w for _ in range(h)]
dic={}
dic[0]=0
dic[(0,1)]=(0,-1)
dic[(0,-1)]=(0,1)
dic[(1,0)]=(-1,0)
dic[(-1,0)]=(1,0)

maze[y1-1][x1-1]=0
#pri(maze)
while len(stack)>0:
    #print(stack)
    (y,x)=stack.popleft()
    if (y,x)==(y2-1,x2-1):
        print(maze[y][x])
        exit()

    #縦横左右
    for (my,mx) in ((1,0),(0,1),(-1,0),(0,-1)):
        #print(my,mx)
        flag=0
        if (my,mx)!=dic[before[y][x]]:
            for kk in range(1,k+1):
                ny=y+my*kk
                nx=x+mx*kk
                if 0<=ny<h and 0<=nx<w:
                    if maze[ny][nx]!="@":
                        if maze[ny][nx]==".":
                            maze[ny][nx]=maze[y][x]+1
                            stack.append((ny,nx))
                            before[ny][nx]=((my,mx))
                        if maze[ny][nx]==maze[y][x]+1:
                            continue
                        else:
                            break
                    else:
                        break
                else:
                    break
    #pri(maze)
print(-1)

Submission status: Accepted

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      if reach[nx][ny] + 1 == reach[tx][ty]:
        #同じときはQに加える必要はないが、そのまま先に進んだら得の場合があるのでContinue
        continue
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
      if tx == gx and ty == gy:
        print(reach[gx][gy])
        exit()
#print(reach)
#ans = reach[gx][gy]
#if ans == INF:
print(-1)
#else:
#  print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      if reach[nx][ny] + 1 == reach[tx][ty]:
        continue
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
      if tx == gx and ty == gy:
        print(reach[gx][gy])
        exit()
#print(reach)
#ans = reach[gx][gy]
#if ans == INF:
print(-1)
#else:
#  print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W,K= map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1 #0index
Pond = []
for i in range(H):
  temp = str(input())
  temp = list(temp)
  Pond.append(temp)
#print(Pond)
INF = float("inf")
reach = [[INF for _ in range(W)] for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
Q = deque([(sx,sy)])
while Q:
  x,y = Q.popleft()
  #print(x,y)
  #step = reach[x][y]
  for j in range(4):
    for i in range(1,K+1):
      fac = i
      nx = x+fac*dxdy[j][0]
      ny = y+fac*dxdy[j][1]
      #print(nx,ny)
      if nx<0 or nx>=H or ny<0 or ny>= W or Pond[nx][ny] == "@":
        break
      if reach[x][y]+1 > reach[nx][ny]: #すでに余裕をもって到達済み
        break
      if reach[x][y]+1 < reach[nx][ny]:
        reach[nx][ny] = min(reach[x][y]+1,reach[nx][ny])
        Q.append((nx,ny))
      if nx == gx and ny == gy:
        #print(reach)
        print(reach[nx][ny])
        exit()
print(-1)

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

def bfs(sl, visited, sy, sx, gy, gx, h, w, k):
    q = deque([ (sy,sx) ])
    visited[sy][sx] = 0
    while q:
        # print(q)
        y, x = q.popleft()
        if [y, x] == [gy, gx]:
            return visited[gy][gx]
        for i in range(1,k+1):
            ny = y+i
            if ny >= h:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            if visited[ny][x] != visited[y][x]+1: 
                visited[ny][x] = visited[y][x]+1
                q.append((ny,x))

        for i in range(1,k+1):
            ny = y-i
            if ny < 0:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            if visited[ny][x] != visited[y][x]+1: 
                visited[ny][x] = visited[y][x]+1
                q.append((ny,x))

        for i in range(1,k+1):
            nx = x+i
            if nx >= w:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            if visited[y][nx] != visited[y][x]+1: 
                visited[y][nx] = visited[y][x]+1
                q.append((y,nx))

        for i in range(1,k+1):
            nx = x-i
            if nx < 0:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            if visited[y][nx] != visited[y][x]+1: 
                visited[y][nx] = visited[y][x]+1
                q.append((y,nx))

    return -1

def main():
    h,w,k = map(int, input().split())
    x1,y1,x2,y2 = map(int, input().split())
    cl = []
    for i in range(h):
        row = list(input())
        cl.append(row)

    visited = [ [-1]*w for i in range(h)]
    ans = bfs(cl, visited, x1-1,y1-1,x2-1,y2-1,h,w,k)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
d = [[1, 0], [-1, 0], [0, -1], [0, 1]]
h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
c = [list(input()) for i in range(h)]
visited = [[-1] * w for i in range(h)]
visited[x1 - 1][y1 - 1] = 0
Q = deque([(x1 - 1, y1 - 1)])
while Q:
    nx, ny = Q.popleft()
    if nx == x2 - 1 and ny == y2 - 1:
        exit(print(visited[nx][ny]))
    for dx, dy in d:
        for i in range(k):
            p, q = nx + dx * (i + 1), ny + dy * (i + 1)
            if not (0 <= p < h and 0 <= q < w) or c[p][q] == "@":
                break
            if 0 <= visited[p][q] <= visited[nx][ny]:
                break
            if visited[p][q] == -1:
                Q.append((p, q))
            visited[p][q] = visited[nx][ny] + 1
print(-1)

Submission status: Accepted

Solution code:
from collections import deque

def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    M = []
    Cost = [[1000000] * W for i in range(H)]
    dxdy = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    Cost[x1-1][y1-1] = 0
    q = deque([(x1-1, y1-1)])
    for h in range(H):
        M.append(list(input()))

    while q:
        x, y = q.popleft()
        for ddx, ddy in dxdy:
            for i in range(1, K+1):
                dx = ddx*i
                dy = ddy*i

                if not (0 <= x+dx < H and 0 <= y+dy < W):
                    break
                if M[x+dx][y+dy] == '@' or Cost[x+dx][y+dy] <= Cost[x][y]:
                    break
                if x+dx == x2-1 and y+dy == y2-1:
                    print(Cost[x][y]+1)
                    exit(0)
                if Cost[x+dx][y+dy] > Cost[x][y] + 1:
                    Cost[x+dx][y+dy] = Cost[x][y] + 1
                    q.append((x+dx,y+dy))
    

    print(-1)

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
h,w,k=map(int,input().split())
sy,sx,gy,gx=map(int,input().split())
G=[["@"]*(w+2) for i in range(h+2)]
for i in range(1,h+1):
  G[i]=["@"]+list(input())+["@"]
V=[[10**10]*(w+2) for i in range(h+2)]
V[sy][sx]=0
D=[[[0,0,0,0] for j in range(w+2)] for i in range(h+2)]
D[sy][sx]=[1,1,1,1]
X=deque([])
Y=deque([])
i=1
while G[sy-i][sx]==".":
  Y.append(sy-i)
  X.append(sx)
  V[sy-i][sx]=1
  D[sy-i][sx][0]=1
  D[sy-i][sx][1]=1
  if i==k:
    D[sy-i][sx][0]=0
    break
  i=i+1
i=1
while G[sy+i][sx]==".":
  Y.append(sy+i)
  X.append(sx)
  V[sy+i][sx]=1
  D[sy+i][sx][0]=1
  D[sy+i][sx][1]=1
  if i==k:
    D[sy+i][sx][1]=0
    break
  i=i+1

i=1
while G[sy][sx-i]==".":
  Y.append(sy)
  X.append(sx-i)
  V[sy][sx-i]=1
  D[sy][sx-i][2]=1
  D[sy][sx-i][3]=1
  if i==k:
    D[sy][sx-i][2]=0
    break
  i=i+1
i=1
while G[sy][sx+i]==".":
  Y.append(sy)
  X.append(sx+i)
  V[sy][sx+i]=1
  D[sy][sx+i][2]=1
  D[sy][sx+i][3]=1
  if i==k:
    D[sy][sx+i][3]=0
    break
  i=i+1

def yn(yy,xx):
  D[yy][xx][0]=1
  i=1
  while G[yy-i][xx]==".":
    if V[yy][xx]+1>V[yy-i][xx]:
      break
    D[yy-i][xx][0]=1
    D[yy-i][xx][1]=1
    V[yy-i][xx]=V[yy][xx]+1
    if i==k:
      D[yy-i][xx][0]=0
      Y.append(yy-i)
      X.append(xx)
      break
#    if D[yy-i][xx]!=[1,1,1,1]:
    Y.append(yy-i)
    X.append(xx)
    i=i+1


def yp(yy,xx):
  D[yy][xx][1]=1
  i=1
  while G[yy+i][xx]==".":
    if V[yy][xx]+1>V[yy+i][xx]:
      break
    D[yy+i][xx][0]=1
    D[yy+i][xx][1]=1
    V[yy+i][xx]=min(V[yy+i][xx],V[yy][xx]+1)
    if i==k:
      D[yy+i][xx][1]=0
      Y.append(yy+i)
      X.append(xx)
      break
#    if D[yy+i][xx]!=[1,1,1,1]:
    Y.append(yy+i)
    X.append(xx)
    i=i+1


def xn(yy,xx):
  D[yy][xx][2]=1
  i=1
  while G[yy][xx-i]==".":
    if V[yy][xx]+1>V[yy][xx-i]:
      break
    D[yy][xx-i][2]=1
    D[yy][xx-i][3]=1
    V[yy][xx-i]=min(V[yy][xx-i],V[yy][xx]+1)
    if i==k:
      D[yy][xx-i][2]=0
      Y.append(yy)
      X.append(xx-i)
      break
#    if D[yy][xx-i]!=[1,1,1,1]:
    Y.append(yy)
    X.append(xx-i)
    i=i+1


def xp(yy,xx):
  D[yy][xx][3]=1
  i=1
  while G[yy][xx+i]==".":
    if V[yy][xx]+1>V[yy][xx+i]:
      break
    D[yy][xx+i][2]=1
    D[yy][xx+i][3]=1
    V[yy][xx+i]=min(V[yy][xx+i],V[yy][xx]+1)
    if i==k:
      D[yy][xx+i][3]=0
      Y.append(yy)
      X.append(xx+i)
      break
#    if D[yy][xx+i]!=[1,1,1,1]:
    Y.append(yy)
    X.append(xx+i)
    i=i+1

while len(X)>0:
  x=X[0]
  y=Y[0]
  X.popleft()
  Y.popleft()
  if D[y][x][0]==0:
    yn(y,x)
  if D[y][x][1]==0:
    yp(y,x)
  if D[y][x][2]==0:
    xn(y,x)
  if D[y][x][3]==0:
    xp(y,x)

if V[gy][gx]==10**10:
  print(-1)
else:
  print(V[gy][gx])

Submission status: Accepted

Solution code:
from collections import deque
h, w, k = map(int, input().split())
y1, x1, y2, x2 = map(int, input().split())
c = []
for _ in range(h):
    c.append(input())
q = deque([(x1-1, y1-1)])
dxdy = [(-1,0), (0,-1), (0,1), (1,0)]
dist = [[1000000]*w for _ in range(h)]
dist[y1-1][x1-1] = 0
while q:
    x, y = q.popleft()
    for ddx, ddy in dxdy:
        for i in range(1, k+1):
            dx = ddx*i
            dy = ddy*i
            if not (0<=x+dx<w and 0<=y+dy<h):
                break
            if c[y+dy][x+dx]=='@' or dist[y+dy][x+dx]<=dist[y][x]:
                break
            if x+dx==x2-1 and y+dy==y2-1:
                print(dist[y][x]+1)
                exit(0)
            if dist[y+dy][x+dx]>dist[y][x]+1:
                dist[y+dy][x+dx] = dist[y][x]+1
                q.append((x+dx, y+dy))
print(-1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


def bfs(i1, j1) -> list:
    U, D, L, R = 0, 1, 2, 3
    INF = 10 ** 18
    dist = [[INF] * w for _ in range(h)]
    dist[i1][j1] = 0
    q = deque([(0, i1, j1)])
    while q:
        d, i, j = q.popleft()
        #if dist[i][j] < d:
        #    continue
        for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            for length in range(1, k + 1):
                nxt_i = i + di * length
                nxt_j = j + dj * length
                if not(0 <= nxt_i < h and 0 <= nxt_j < w):
                    break
                if c[nxt_i][nxt_j] == "@":
                    break
                if dist[i][j] + 1 > dist[nxt_i][nxt_j]:
                    break
                if dist[i][j] + 1 < dist[nxt_i][nxt_j]:
                    dist[nxt_i][nxt_j] = dist[i][j] + 1
                    q.append((dist[nxt_i][nxt_j], nxt_i, nxt_j))
    return dist


h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
c = [input() for i in range(h)]


x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
dist = bfs(x1, y1)
ans = dist[x2][y2]

if ans == 10 ** 18:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

h,w,k = inm()
x1,y1,x2,y2 = inm()
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = []
for i in range(h):
    c.append(ins())
d = [[-1]*w for i in range(h)]
q = deque([(x1,y1)])
d[x1][y1] = 0
dir = [(0,1),(0,-1),(1,0),(-1,0)]
while len(q)>0:
    x,y = q.popleft()
    dd = d[x][y]+1
    for dx,dy in dir:
        for i in range(1,k+1):
            xx = x+i*dx
            yy = y+i*dy
            if xx<0 or h<=xx or yy<0 or w<=yy or \
               (d[xx][yy]>=0 and d[xx][yy]<dd) or c[xx][yy]=='@':
                break
            if d[xx][yy] == dd:
                continue
            d[xx][yy] = dd
            q.append((xx,yy))
            if xx==x2 and yy==y2:
                print(dd)
                exit()
print(-1)

Submission status: Accepted

Solution code:
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
sh, sw, gh, gw = sh - 1, sw - 1, gh - 1, gw - 1
G = [list(input()) for _ in range(H)]
INF = 10 ** 9


D = [[INF] * W for _ in range(H)]
D[sh][sw] = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
que = deque([(sh, sw)])

while que:
    nh, nw = que.pop()
    for dh, dw in directions:
        for k in range(1, K + 1):
            nx_h, nx_w = nh + k * dh, nw + k * dw
            if not (0 <= nx_h < H and 0 <= nx_w < W):
                break

            if G[nx_h][nx_w] == '@':
                break

            if D[nx_h][nx_w] < D[nh][nw] + 1:
                break

            if D[nx_h][nx_w] > D[nh][nw] + 1:
                D[nx_h][nx_w] = D[nh][nw] + 1
                que.appendleft((nx_h, nx_w))

print(D[gh][gw] if D[gh][gw] != INF else -1)

Submission status: Accepted

Solution code:
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
sh, sw, gh, gw = sh - 1, sw - 1, gh - 1, gw - 1
G = [list(input()) for _ in range(H)]
INF = 10 ** 9


D = [[INF] * W for _ in range(H)]
D[sh][sw] = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
que = deque([(sh, sw)])

while que:
    nh, nw = que.pop()
    for dh, dw in directions:
        for k in range(1, K + 1):
            nx_h, nx_w = nh + k * dh, nw + k * dw
            if not (0 <= nx_h < H and 0 <= nx_w < W):
                break

            if G[nx_h][nx_w] == '@':
                break

            if D[nx_h][nx_w] <= D[nh][nw]:
                break

            if D[nx_h][nx_w] > D[nh][nw] + 1:
                D[nx_h][nx_w] = D[nh][nw] + 1
                que.appendleft((nx_h, nx_w))

print(D[gh][gw] if D[gh][gw] != INF else -1)

Submission status: Accepted

Solution code:
import queue
import sys
input = sys.stdin.readline

def calc_next_point(x, y, vec, dist):
    if vec == 0:
        return x-dist, y
    elif vec == 1:
        return x, y+dist
    elif vec == 2:
        return x+dist, y
    else:
        return x, y-dist

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[[-1]*4 for j in range(w+2)] for i in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                for l in range(4):
                    pond[i][j+1][l] = float("inf")
    qs = [queue.Queue(), queue.Queue()]
    for i in range(4):
        pond[x1][y1][i] = 0
        qs[0].put([0, x1, y1, i])
    p = 0
    minans = float("inf")
    g = False
    while not qs[0].empty() or not qs[1].empty():
        while not qs[p].empty():
            cost, x, y, vec = qs[p].get()
            np = (p+1)%2
            if cost >= minans:
                g = True
                break
            if x == x2 and y == y2:
                if cost < minans:
                    minans = cost
                g = True
                break
            for i in range(1, k+1):
                nx, ny = calc_next_point(x, y, vec, i)
                if pond[nx][ny][vec] == -1:
                    break
                ncost = cost + 1
                if pond[nx][ny][vec] < ncost:
                    break
                if pond[nx][ny][vec] == ncost:
                    continue
                pond[nx][ny][vec] = ncost
                if nx == x2 and ny == y2:
                    if ncost < minans:
                        minans = ncost
                    g = True
                    break
                for j in range(4):
                    if i == k:
                        if j != (vec+2)%4:
                            if j == vec or pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
                    elif i == 1:
                        if j != vec:
                            if j == (vec+2)%4 or pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
                    else:
                        if j != vec and j != (vec+2)%4:
                            if pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
            if g:
                break
        if g:
            break
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()