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: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=h*w]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j;p=d[s]+1
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<p:break
   if d[t]==I:q+=t,;d[t]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
I=h*w
d=[I]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   if~d[t]-I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
I=h*w
d=[I]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   if~d[t]-I:q+=t,
   d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=h*w]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   if d[t]==I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    W = W+2
    c = [["@"]*W]
    for i in range(H):
        c.append(["@"]+list(input())+["@"])
    c.append(["@"]*W)
    H = H+2

    DX = [1, 0, -1,  0]
    DY = [0, 1, 0, -1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[-1]*W for _ in range(H)]
    dist[x1][y1] = 0
    # ヒープでなくて良い。
    # 高々1しか加わっていかないため、キューに加えられた順で十分昇順になる。
    Q = [(0, x1, y1, 0)]
    Q += [(0, x1, y1, 1)]
    Q += [(0, x1, y1, 2)]
    Q += [(0, x1, y1, 3)]
    i = 0
    while i < len(Q):
        curr, x, y, DXY = Q[i]
        c[x][y] = "@"
        dx, dy = DX[DXY], DY[DXY]
        for k in range(1, K+1):
            X, Y = x+k*dx, y+k*dy
            if c[X][Y] == "@":
                break
            if 0 < dist[X][Y] < curr+1:
                break
            # if dist[X][Y] == curr+1:
            #     continue
            dist[X][Y] = curr+1
            Q.append((curr+1, X, Y, (DXY+1) % 4))
            Q.append((curr+1, X, Y, (DXY-1) % 4))
        else:
            Q.append((curr+1, X, Y, DXY))
        if 0 < dist[x2][y2]:
            print(dist[x2][y2])
            return
        i += 1
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    W = W+2
    c = [["@"]*W]
    for i in range(H):
        c.append(["@"]+list(input())+["@"])
    c.append(["@"]*W)
    H = H+2

    DX = [1, 0, -1,  0]
    DY = [0, 1, 0, -1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[-1]*W for _ in range(H)]
    dist[x1][y1] = 0
    # ヒープでなくて良い。
    # 高々1しか加わっていかないため、キューに加えられた順で十分昇順になる。
    Q = [(0, x1, y1, 0)]
    Q += [(0, x1, y1, 1)]
    Q += [(0, x1, y1, 2)]
    Q += [(0, x1, y1, 3)]
    i = 0
    while i < len(Q):
        curr, x, y, DXY = Q[i]
        c[x][y] = "@"
        dx, dy = DX[DXY], DY[DXY]
        for k in range(1, K+1):
            X, Y = x+k*dx, y+k*dy
            if c[X][Y] == "@":
                break
            # if 0 < dist[X][Y] < curr+1:
            #     break
            # if dist[X][Y] == curr+1:
            #     continue
            dist[X][Y] = curr+1
            Q.append((curr+1, X, Y, (DXY+1) % 4))
            Q.append((curr+1, X, Y, (DXY-1) % 4))
        else:
            Q.append((curr+1, X, Y, DXY))
        if 0 < dist[x2][y2]:
            print(dist[x2][y2])
            return
        i += 1
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
I=h*w
d=[I]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<d[s]:break
   if d[t]==I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
# F - Pond Skater

from collections import deque

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

dist = [[-1] * W for _ in range(H)]
dist[x1][y1] = 0
q = deque()
q.append((x1, y1))

while q:
    (x, y) = q.popleft()
    if (x, y) == (x2, y2):
        break
    for vx, vy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        for k in range(1, K+1):
            nx = x + vx*k
            ny = y + vy*k
            if nx < 0 or nx >= H or ny < 0 or ny >= W or grid[nx][ny] == '@':
                break
            if dist[nx][ny] == -1:
                dist[nx][ny] = dist[x][y] + 1
                q.append((nx, ny))

print(dist[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=h*w]*I
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   if d[t]==I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=9**9]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   if d[t]==I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=9**9]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   if(h>(i:=s//w+y*~z)>-1<(j:=s%w+x*~z)<w)-1or'.'<m[i][j]or d[(t:=i*w+j)]<=d[s]:break
   if d[t]==I:q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a,f=~w+a*w+b,~w+f*w+g
d[a]=1
q=[a]
for s in q:
 if s==f:break
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   q+=t,;d[t]=d[s]+1
print(d[f]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
def S():
 h,a,*m=open(0)
 h,w,k,a,b,f,g=map(int,(h+a).split())
 d=[I]*h*w
 a=~w+a*w+b
 d[a]=1
 q=[a]
 for s in q:
  for y,x in(1,0),(-1,0),(0,1),(0,-1):
   for z in range(k):
    i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
    if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
    q+=t,;d[t]=d[s]+1
 print(d[~w+f*w+g]%I-1)
S()

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
e=q.append
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   e(t);d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,-1),(0,1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or d[t]<=d[s]or'.'<m[i][j]:break
   q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<=d[s]:break
   q+=t,;d[t]=d[s]+1
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 o,p,u=s//w,s%w,d[s]+1
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=o+y*~z,p+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<u:break
   q+=t,;d[t]=u
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
a=~w+a*w+b
d[a]=1
q=[a]
for s in q:
 p=d[s]+1
 for y,x in(1,0),(-1,0),(0,1),(0,-1):
  for z in range(k):
   i,j=s//w+y*~z,s%w+x*~z;t=i*w+j
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[t]<p:break
   q+=t,;d[t]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q.append((i,j));d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=[(i,j)];d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = []
    for i in range(H):
        c.append(input())
    # 移動方法が4*K個考えられる無向グラフ
    # 到達可能性は最短経路を求めるだけでよい
    # 全ての箇所を探索するとO(H*W)必要に見える。
    # あれ、HW<=10^6がある。難しさは何？Kが大きいから枝が多すぎるということか。
    DX = [1, 0, -1,  0]
    DY = [0, 1, 0, -1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[INF]*W for _ in range(H)]
    dist[x1][y1] = 0
    Q = []                      # ヒープなんてもう知らない！
    M = 10**6
    Q.append((0, x1*M+y1, 0b1111))
    i = 0

    while i < len(Q):
        curr, xy, DXY = Q[i]
        x, y = divmod(xy, M)
        for j in range(4):
            if (DXY >> j) & 1 == 0:
                continue
            dx, dy = DX[j], DY[j]
            for k in range(1, K+1):
                X = x+k*dx
                Y = y+k*dy
                if not (0 <= X < H):
                    break
                if not (0 <= Y < W):
                    break
                if dist[X][Y] < curr+1:
                    break
                if c[X][Y] == "@":
                    break
                dist[X][Y] = curr+1
                flag = (1 << ((j+1) % 4)) | (1 << ((j-1) % 4))
                if k != K:
                    Q.append((curr+1, X*M+Y, flag))
                else:
                    flag |= 1 << j % 4
                    Q.append((curr+1, X*M+Y, flag))
        if dist[x2][y2] < INF:
            print(dist[x2][y2])
            # print(*dist, sep="\n")
            return
        i += 1
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in[1,0],[-1,0],[0,1],[0,-1]:
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = []
    for i in range(H):
        c.append(input())
    # 移動方法が4*K個考えられる無向グラフ
    # 到達可能性は最短経路を求めるだけでよい
    # 全ての箇所を探索するとO(H*W)必要に見える。
    # あれ、HW<=10^6がある。難しさは何？Kが大きいから枝が多すぎるということか。
    DX = [1, 0, -1,  0]
    DY = [0, 1, 0, -1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[INF]*W for _ in range(H)]
    dist[x1][y1] = 0
    Q = []                      # ヒープなんてもう知らない！
    Q.append((0, (x1, y1), 0b1111))
    i = 0

    while i < len(Q):
        curr, (x, y), DXY = Q[i]
        # print([1 & (DXY >> l) for l in range(4)])
        for j in range(4):
            if (DXY >> j) & 1 == 0:
                continue
            dx, dy = DX[j], DY[j]
            for k in range(1, K+1):
                X = x+k*dx
                Y = y+k*dy
                if not (0 <= X < H):
                    break
                if not (0 <= Y < W):
                    break
                if dist[X][Y] < curr+1:
                    break
                if c[X][Y] == "@":
                    break
                dist[X][Y] = curr+1
                flag = (1 << ((j+1) % 4)) | (1 << ((j-1) % 4))
                if k != K:
                    Q.append((curr+1, (X, Y), flag))
                else:
                    flag |= 1 << j % 4
                    Q.append((curr+1, (X, Y), flag))
        if dist[x2][y2] < INF:
            print(dist[x2][y2])
            # print(*dist, sep="\n")
            return
        i += 1
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 if s==f-1and t==g-1:break
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W,K = map(int,input().split())
r1,c1,r2,c2 = map(lambda x:int(x)-1,input().split())
C = [input() for i in range(H)]

def solve():
    from collections import deque
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    INF = float('inf')
    dists = [[INF]*W for _ in range(H)]
    dists[r1][c1] = 0
    q = deque([(r1,c1)])
    while q:
        y,x = q.popleft()
        if y==r2 and x==c2:
            print(dists[y][x])
            exit()
        for dx,dy in dxy:
            for i in range(1,K+1):
                nx,ny = x+dx*i,y+dy*i
                if not 0 <= nx < W: break
                if not 0 <= ny < H: break
                if C[ny][nx] == '@': break
                if dists[ny][nx] <= dists[y][x] + 1: continue
                if dists[ny][nx] <= dists[y][x] + 2: break # gori~~
                dists[ny][nx] = dists[y][x] + 1
                q.append((ny,nx))
    print(-1)
solve()

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=9**9]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 if s==f-1and t==g-1:break
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   if(h>(i:=s+y*~z)>-1<(j:=t+x*~z)<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W,K = map(int,input().split())
r1,c1,r2,c2 = map(lambda x:int(x)-1,input().split())
C = [input() for i in range(H)]

def solve():
    from collections import deque
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    INF = float('inf')
    dists = [[INF]*W for _ in range(H)]
    dists[r1][c1] = 0
    q = deque([(r1,c1)])
    while q:
        y,x = q.popleft()
        if y==r2 and x==c2:
            print(dists[y][x])
            exit()
        for dx,dy in dxy:
            for i in range(1,K+1):
                nx,ny = x+dx*i,y+dy*i
                if not 0 <= nx < W: break
                if not 0 <= ny < H: break
                if C[ny][nx] == '@': break
                if dists[ny][nx] <= dists[y][x] + 1: continue
                if dists[ny][nx] <= dists[y][x] + 4: break # gori~~
                dists[ny][nx] = dists[y][x] + 1
                q.append((ny,nx))
    print(-1)
solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W,K = map(int,input().split())
r1,c1,r2,c2 = map(lambda x:int(x)-1,input().split())
C = [input() for i in range(H)]

def solve():
    from collections import deque
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    INF = float('inf')
    dists = [[INF]*W for _ in range(H)]
    dists[r1][c1] = 0
    q = deque([(r1,c1)])
    while q:
        y,x = q.popleft()
        if y==r2 and x==c2:
            print(dists[y][x])
            exit()
        for dx,dy in dxy:
            for i in range(1,K+1):
                nx,ny = x+dx*i,y+dy*i
                if not 0 <= nx < W: break
                if not 0 <= ny < H: break
                if C[ny][nx] == '@': break
                if dists[ny][nx] <= dists[y][x] + 1: continue
                if dists[ny][nx] <= dists[y][x] + 10: break # gori~~
                dists[ny][nx] = dists[y][x] + 1
                q.append((ny,nx))
    print(-1)
solve()

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=2**30]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   if(h>(i:=s+y*~z)>-1<(j:=t+x*~z)<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W,K = map(int,input().split())
r1,c1,r2,c2 = map(lambda x:int(x)-1,input().split())
C = [input() for i in range(H)]

def solve():
    from collections import deque
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    INF = float('inf')
    dists = [[INF]*W for _ in range(H)]
    dists[r1][c1] = 0
    q = deque([(r1,c1)])
    while q:
        y,x = q.popleft()
        if y==r2 and x==c2:
            print(dists[y][x])
            exit()
        for dx,dy in dxy:
            for i in range(1,K+1):
                nx,ny = x+dx*i,y+dy*i
                if not 0 <= nx < W: break
                if not 0 <= ny < H: break
                if C[ny][nx] == '@': break
                if dists[ny][nx] <= dists[y][x] + 1: continue
                dists[ny][nx] = dists[y][x] + 1
                q.append((ny,nx))
    print(-1)
solve()

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(1,0),(-1,0),(0,-1),(0,1):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(1,0),(0,-1),(0,1):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = []
    for i in range(H):
        c.append(input())
    # 移動方法が4*K個考えられる無向グラフ
    # 到達可能性は最短経路を求めるだけでよい
    # 全ての箇所を探索するとO(H*W)必要に見える。
    # あれ、HW<=10^6がある。難しさは何？Kが大きいから枝が多すぎるということか。
    DX = [-1, +1,  0,  0]
    DY = [0,  0, -1, +1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[INF]*W for _ in range(H)]
    dist[x1][y1] = 0
    Q = []                      # ヒープなんてもう知らない！
    Q.append((0, (x1, y1), (+1, 0)))
    Q.append((0, (x1, y1), (-1, 0)))
    Q.append((0, (x1, y1), (0, +1)))
    Q.append((0, (x1, y1), (0, -1)))
    i = 0
    while i < len(Q):
        curr, (x, y), (dx, dy) = Q[i]
        elseflag = False
        for k in range(1, K+1):
            X = x+k*dx
            Y = y+k*dy
            if not (0 <= X < H):
                break
            if not (0 <= Y < W):
                break
            if dist[X][Y] < curr+1:
                break
            if c[X][Y] == "@":
                break
            dist[X][Y] = curr+1
            Q.append((curr+1, (X, Y), (dy, dx)))
            Q.append((curr+1, (X, Y), (-dy, -dx)))
        else:
            # breakしなかったなら、同一方向をヒープへ追加
            Q.append((curr+1, (X, Y), (dx, dy)))
        if dist[x2][y2] < INF:
            print(dist[x2][y2])
            return
        i += 1
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W,K = map(int,input().split())
r1,c1,r2,c2 = map(lambda x:int(x)-1,input().split())
C = [input() for i in range(H)]

from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]
INF = float('inf')
dists = [[INF]*W for _ in range(H)]
dists[r1][c1] = 0
q = deque([(r1,c1)])
while q:
    y,x = q.popleft()
    if y==r2 and x==c2:
        print(dists[y][x])
        exit()
    for dx,dy in dxy:
        for i in range(1,K+1):
            nx,ny = x+dx*i,y+dy*i
            if not 0 <= nx < W: break
            if not 0 <= ny < H: break
            if C[ny][nx] == '@': break
            if dists[ny][nx] <= dists[y][x] + 1: continue
            dists[ny][nx] = dists[y][x] + 1
            q.append((ny,nx))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
I=9**9
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=9**9]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   i,j=s+y*~z,t+x*~z
   if(h>i>-1<j<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
h,a,*m=open(0)
h,w,k,a,b,f,g=map(int,(h+a).split())
d=[I:=9**9]*h*w
d[~w+a*w+b]=1
q=[(a-1,b-1)]
for s,t in q:
 p=d[s*w+t]+1
 for y,x in(-1,0),(0,-1),(0,1),(1,0):
  for z in range(k):
   if(h>(i:=s+y*~z)>-1<(j:=t+x*~z)<w)-1or'.'<m[i][j]or d[i*w+j]<p:break
   q+=(i,j),;d[i*w+j]=p
print(d[~w+f*w+g]%I-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import heapq
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = []
    for i in range(H):
        c.append(input())
    # 移動方法が4*K個考えられる無向グラフ
    # 到達可能性は最短経路を求めるだけでよい
    # 全ての箇所を探索するとO(H*W)必要に見える。
    # あれ、HW<=10^6がある。難しさは何？Kが大きいから枝が多すぎるということか。
    DX = [-1, +1,  0,  0]
    DY = [0,  0, -1, +1]

    # 方向付きで、ダイクストラ法を使います。
    dist = [[INF]*W for _ in range(H)]
    dist[x1][y1] = 0
    Q = []
    heapq.heappush(Q, (0, (x1, y1), (+1, 0)))
    heapq.heappush(Q, (0, (x1, y1), (-1, 0)))
    heapq.heappush(Q, (0, (x1, y1), (0, +1)))
    heapq.heappush(Q, (0, (x1, y1), (0, -1)))
    while Q:
        curr, (x, y), (dx, dy) = heapq.heappop(Q)
        elseflag = False
        for k in range(1, K+1):
            X = x+k*dx
            Y = y+k*dy
            if not (0 <= X < H):
                break
            if not (0 <= Y < W):
                break
            if dist[X][Y] < curr+1:
                break
            if c[X][Y] == "@":
                break
            dist[X][Y] = curr+1
            # 直交方向へ探索するようヒープに追加
            heapq.heappush(Q, (curr+1, (X, Y), (dy, dx)))
            heapq.heappush(Q, (curr+1, (X, Y), (-dy, -dx)))
        else:
            # breakしなかったなら、同一方向をヒープへ追加
            heapq.heappush(Q, (curr+1, (X, Y), (dx, dy)))
        if dist[x2][y2] < INF:
            print(dist[x2][y2])
            return
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import heapq
INF = float("inf")


def main():
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
    c = []
    for i in range(H):
        c.append(input())
    # 移動方法が4*K個考えられる無向グラフ
    # 到達可能性は最短経路を求めるだけでよい
    # 全ての箇所を探索するとO(H*W)必要に見える。
    # あれ、HW<=10^6がある。難しさは何？Kが大きいから枝が多すぎるということか。
    DX = [-1, +1,  0,  0]
    DY = [0,  0, -1, +1]

    # ダイクストラ法を使います。
    dist = [[INF]*W for _ in range(H)]
    dist[x1][y1] = 0
    Q = [(0, (x1, y1))]
    while Q:
        curr, (x, y) = heapq.heappop(Q)
        for dx, dy in zip(DX, DY):
            for k in range(1, K+1):
                # ヒープキューで管理していることから考えると
                # 値が存在する場所と比較しても更新できることはない。
                X = x+k*dx
                Y = y+k*dy
                if not (0 <= X < H):
                    break
                if not (0 <= Y < W):
                    break
                if dist[X][Y] < curr+1:
                    break
                if c[X][Y] == "@":
                    break
                # これ実質的に距離はcurrだけでよいのだけど
                dist[X][Y] = curr+1
                heapq.heappush(Q, (curr+1, (X, Y)))
        if dist[x2][y2] < INF:
            print(dist[x2][y2])
            # print(*dist, sep="\n")
            return
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h,w,k = map(int, input().split())
sx,sy,gx,gy = map(lambda x: int(x)-1, input().split())
board = [list(map(lambda x: int(x=="."), input())) for i in range(h)]
inf = 1<<30
DP = [[inf for j in range(w)] for i in range(h)]
DP[sx][sy] = 0

que = [(sx,sy)]
dxdy = [(0,1),(1,0),(0,-1),(-1,0)]
for x,y in que:
    for dx,dy in dxdy:
        nx,ny = x,y
        for i in range(k):
            nx += dx
            ny += dy
            if not(0<=nx<h and 0<=ny<w and board[nx][ny] and DP[nx][ny] >= DP[x][y]+1):
                break
            if DP[nx][ny] > DP[x][y]+1:
                DP[nx][ny] = DP[x][y]+1
            que.append((nx,ny))
ans = DP[gx][gy]
if ans == inf:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,k = map(int, input().split())
sx,sy,gx,gy = map(lambda x: int(x)-1, input().split())
board = [list(map(lambda x: int(x=="."), input())) for i in range(h)]
inf = 1<<30
DP = [[inf for j in range(w)] for i in range(h)]
DP[sx][sy] = 0

from collections import deque
que = deque([(sx,sy)])

dxdy = [(0,1),(1,0),(0,-1),(-1,0)]
while que:
    x,y = que.popleft()
    for dx,dy in dxdy:
        nx,ny = x,y
        for i in range(k):
            nx += dx
            ny += dy
            if not(0<=nx<h and 0<=ny<w and board[nx][ny] and DP[nx][ny] >= DP[x][y]+1):
                break
            if DP[nx][ny] > DP[x][y]+1:
                DP[nx][ny] = DP[x][y]+1
            que.append((nx,ny))
ans = DP[gx][gy]
if ans == inf:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,k = map(int, input().split())
sx,sy,gx,gy = map(lambda x: int(x)-1, input().split())
board = [list(map(lambda x: int(x=="."), input())) for i in range(h)]
inf = 1<<30
DP = [[inf for j in range(w)] for i in range(h)]
DP[sx][sy] = 0

from collections import deque
que = deque([(sx,sy)])

dxdy = [(0,1),(1,0),(0,-1),(-1,0)]
while que:
    x,y = que.popleft()
    for dx,dy in dxdy:
        nx,ny = x,y
        for i in range(k):
            nx += dx
            ny += dy
            if not(0<=nx<h and 0<=ny<w and board[nx][ny] and DP[nx][ny] >= DP[x][y]+1):
                break
            DP[nx][ny] = min(DP[nx][ny], DP[x][y]+1)
            que.append((nx,ny))
ans = DP[gx][gy]
if ans == inf:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

h,w,k = map(int, input().split())
x1,y1,x2,y2 = map(int, input().split())
x1,y1,x2,y2 = x1-1,y1-1, x2-1,y2-1
board = [list(map(lambda x: int(x=="."), input())) for i in range(h)]

def make_array(dims, fill):
    if len(dims) == 1:
        return [fill]*dims[0]
    nxt = dims[1:]
    ret = [make_array(nxt,fill) for i in range(dims[0])]
    return ret

inf = 1<<30

DP = make_array((h,w,4), inf)

from collections import deque
que = deque()
for i in range(4):
    que.append((x1,y1,i,0))

dxdy = [(-1,0),(1,0),(0,1),(0,-1)]
while que:
    x,y,prev,cost = que.popleft()
    if DP[x][y][prev] <= cost:
        continue
    DP[x][y][prev] = cost
    for i in range(4):
        if i == prev:
            continue
        nprev = i^1
        ddx, ddy = dxdy[i]
        for j in range(1,k+1):
            nx, ny = x+j*ddx, y+j*ddy
            if not (0<=nx<h and 0<=ny<w and board[nx][ny] and DP[nx][ny][nprev] > cost+1):
                break
            que.append((nx,ny,nprev,cost+1))

ans = min(DP[x2][y2])
if ans == inf:
    print(-1)
else:
    print(ans)