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:
from math import inf

H,W,K=map(int,input().split())
x,y,u,v=map(int,input().split())
M=["N","E","W","S"]
C=[[]]
D={}
E={}

for a in range(H):
    P=input()
    C.append("*"+P)
    for b in range(W):
        if P[b]==".":
            for d in M:
                D[((a+1,b+1),d)]=inf
        

for d in M:
    D[((x,y),d)]=0

L={"N":(1,0),"E":(0,1),"S":(-1,0),"W":(0,-1)}
while D:
    ((p,q),d)=min(D,key=lambda x:D[x])
    g=D[((p,q),d)]
    E[((p,q),d)]=g
    del D[((p,q),d)]

    (a,b)=L[d]
    for m in range(1,K+1):
        X=p+a*m
        Y=q+b*m
        if (1<=X<=H) and (1<=Y<=W):
            if C[X][Y]==".":
                if ((X,Y),d) in D:
                    D[((X,Y),d)]=min(D[((X,Y),d)],g+m)
            else:
                break
        else:
            break

    for t in M:
        if ((p,q),t) in D:
            D[((p,q),t)]=((g+K-1)//K)*K
        
    
if E[((u,v),"N")]==inf:
    print(-1)
else:
    print(E[((u,v),"N")]//K)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf if c[i][j]=="." else -1 for j in range(w)] for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
def bfs(d):
    global h,w,k,dp,now,x2,y2
    l=len(now)
    if l==0:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if dp[x][y+j]==inf:
                dp[x][y+j]=d
                now.append([x,y+j])
            if dp[x][y+j]==-1:
                break
        for j in range(1,min(k+1,y+1)):
            if dp[x][y-j]==inf:
                dp[x][y-j]=d
                now.append([x,y-j])
            if dp[x][y-j]==-1:
                break
        for j in range(1,min(k+1,h-x)):
            if dp[x+j][y]==inf:
                dp[x+j][y]=d
                now.append([x+j,y])
            if dp[x+j][y]==-1:
                break
        for j in range(1,min(k+1,x+1)):
            if dp[x-j][y]==inf:
                dp[x-j][y]=d
                now.append([x-j,y])
            if dp[x-j][y]==-1:
                break
    bfs(d+1)
bfs(1)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf if c[i][j]=="." else -1 for j in range(w)] for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
def bfs(d):
    global h,w,k,dp,now,x2,y2
    l=len(now)
    if l==0:
        return
    if dp[x2-1][y2-1]!=inf and dp[x2-1][y2-1]!=-1:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if dp[x][y+j]==inf:
                dp[x][y+j]=d
                now.append([x,y+j])
            if dp[x][y+j]==-1:
                break
        for j in range(1,min(k+1,y+1)):
            if dp[x][y-j]==inf:
                dp[x][y-j]=d
                now.append([x,y-j])
            if dp[x][y-j]==-1:
                break
        for j in range(1,min(k+1,h-x)):
            if dp[x+j][y]==inf:
                dp[x+j][y]=d
                now.append([x+j,y])
            if dp[x+j][y]==-1:
                break
        for j in range(1,min(k+1,x+1)):
            if dp[x-j][y]==inf:
                dp[x-j][y]=d
                now.append([x-j,y])
            if dp[x-j][y]==-1:
                break
    bfs(d+1)
bfs(1)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf if c[i][j]=="." else -1 for j in range(w)] for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
def bfs(d):
    global h,w,k,dp,now
    l=len(now)
    if l==0:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if dp[x][y+j]==inf:
                dp[x][y+j]=d
                now.append([x,y+j])
            if dp[x][y+j]==-1:
                break
        for j in range(1,min(k+1,y+1)):
            if dp[x][y-j]==inf:
                dp[x][y-j]=d
                now.append([x,y-j])
            if dp[x][y-j]==-1:
                break
        for j in range(1,min(k+1,h-x)):
            if dp[x+j][y]==inf:
                dp[x+j][y]=d
                now.append([x+j,y])
            if dp[x+j][y]==-1:
                break
        for j in range(1,min(k+1,x+1)):
            if dp[x-j][y]==inf:
                dp[x-j][y]=d
                now.append([x-j,y])
            if dp[x-j][y]==-1:
                break
    bfs(d+1)
bfs(1)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf]*w for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
def bfs(d):
    global h,w,k,x1,y1,x2,y2,c,dp,now
    l=len(now)
    if l==0:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if c[x][y+j]==".":
                if dp[x][y+j]==inf:
                    dp[x][y+j]=d
                    now.append([x,y+j])
            else:
                break
        for j in range(1,min(k+1,y+1)):
            if c[x][y-j]==".":
                if dp[x][y-j]==inf:
                    dp[x][y-j]=d
                    now.append([x,y-j])
            else:
                break
        for j in range(1,min(k+1,h-x)):
            if c[x+j][y]==".":
                if dp[x+j][y]==inf:
                    dp[x+j][y]=d
                    now.append([x+j,y])
            else:
                break
        for j in range(1,min(k+1,x+1)):
            if c[x-j][y]==".":
                if dp[x-j][y]==inf:
                    dp[x-j][y]=d
                    now.append([x-j,y])
            else:
                break
    bfs(d+1)
bfs(1)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf]*w for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
def bfs(d):
    global h,w,k,x1,y1,x2,y2,c,dp,now
    l=len(now)
    if l==0:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,k+1):
            if y+j>=w:
                break
            if c[x][y+j]==".":
                if dp[x][y+j]==inf:
                    dp[x][y+j]=d
                    now.append([x,y+j])
            else:
                break
        for j in range(1,k+1):
            if y-j<0:
                break
            if c[x][y-j]==".":
                if dp[x][y-j]==inf:
                    dp[x][y-j]=d
                    now.append([x,y-j])
            else:
                break
        for j in range(1,k+1):
            if x+j>=h:
                break
            if c[x+j][y]==".":
                if dp[x+j][y]==inf:
                    dp[x+j][y]=d
                    now.append([x+j,y])
            else:
                break
        for j in range(1,k+1):
            if x-j<0:
                break
            if c[x-j][y]==".":
                if dp[x-j][y]==inf:
                    dp[x-j][y]=d
                    now.append([x-j,y])
            else:
                break
    bfs(d+1)
bfs(1)
#print(dp)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
from collections import deque
 
H, W, K = map(int,readline().split())
x1, y1, x2, y2 = map(int,readline().split())
x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1
C = read().split()

dist = [[-1]*W for i in range(H)]
dist[x1][y1] = 0
d = deque([[x1, y1]])
dxy= [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
  x, y = d.popleft()
  if (x, y) == (x2, y2):
    print(dist[x][y])
    quit()
  for dx, dy in dxy:
    xx = x; yy = y
    for i in range(K):
      xx += dx; yy += dy
      if 0<=xx<H and 0<=yy<W and C[xx][yy]!='@':
        if 0 <= dist[xx][yy] <= dist[x][y]:
          break
        dist[xx][yy] = dist[x][y] + 1
        d.append([xx, yy])
      else:
        break

print(dist[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = [tuple(input()) for _ in range(h)]
# print(x1, y1)
# print(x2, y2)

dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]
MAX = 10**7
dp = [[[(MAX, MAX)] * 4 for _ in range(w)] for _ in range(h)]

q = [((1, 0, x1, y1, i)) for i in range(4)]

while q:
    c1, c2, x, y, d = heappop(q)
    # print(x, y, d, c1, c2)
    if c1 > dp[x][y][d][0]:
        continue
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if c[nx][ny] == '@':
            continue
        if i == d and c2 < k:
            if dp[nx][ny][i] > (c1, c2 + 1):
                dp[nx][ny][i] = (c1, c2 + 1)
                heappush(q, (c1, c2 + 1, nx, ny, i))
        else:
            if dp[nx][ny][i] > (c1 + 1, 1):
                dp[nx][ny][i] = (c1 + 1, 1)
                heappush(q, (c1 + 1, 1, nx, ny, i))

ans = min(dp[x2][y2][i][0] for i in range(4))
if ans == MAX:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    lake = [['@' for _ in range(W+2)]]

    for _ in range(H):
        c = ['@'] + list(readline().decode('utf-8').strip()) + ['@']
        lake.append(c)
    lake.append(['@' for _ in range(W+2)])

    dist = [[INF] * (W+2) for _ in range(H+2)]
    dx = (1, 0, -1, 0)
    dy = (0, 1, 0, -1)
    Q = deque()
    Q.append((sy, sx))
    dist[sy][sx] = 0
    while Q:
        y,x = Q.popleft()
        if y == gy and x == gx:
            break
        for i in range(4):
            for k in range(1,K+1):
                n_y = y + dy[i] * k
                n_x = x + dx[i] * k

                if lake[n_y][n_x] == '.':
                    if dist[n_y][n_x] > dist[y][x]+1:
                        dist[n_y][n_x] = dist[y][x] + 1
                        Q.append((n_y,n_x))
                    else:
                        continue

                else:
                    break

    if dist[gy][gx] == INF:
        print('-1')
    else:
        print(dist[gy][gx])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = [list(input()) for _ in range(h)]
# print(x1, y1)
# print(x2, y2)

dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]
MAX = 10**7
dp = [[[(MAX, MAX)] * 4 for _ in range(w)] for _ in range(h)]

q = [((1, 0, x1, y1, i)) for i in range(4)]

while q:
    c1, c2, x, y, d = q.pop()
    # print(x, y, d, c1, c2)
    if c1 > dp[x][y][d][0]:
        continue
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if c[nx][ny] == '@':
            continue
        if i == d and c2 < k:
            if dp[nx][ny][i] > (c1, c2 + 1):
                dp[nx][ny][i] = (c1, c2 + 1)
                q.append((c1, c2 + 1, nx, ny, i))
        else:
            if dp[nx][ny][i] > (c1 + 1, 1):
                dp[nx][ny][i] = (c1 + 1, 1)
                q.append((c1 + 1, 1, nx, ny, i))

ans = min(dp[x2][y2][i][0] for i in range(4))
if ans == MAX:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    lake = [['@' for _ in range(W+2)]]

    for _ in range(H):
        c = ['@'] + list(readline().decode('utf-8').strip()) + ['@']
        lake.append(c)
    lake.append(['@' for _ in range(W+2)])

    dist = [[INF] * (W+2) for _ in range(H+2)]
    dx = (1, 0, -1, 0)
    dy = (0, 1, 0, -1)
    Q = deque()
    Q.append((sy, sx))
    dist[sy][sx] = 0
    while Q:
        q = Q.popleft()
        y = q[0]
        x = q[1]
        if y == gy and x == gx:
            continue
        for i in range(4):
            for k in range(1,K+1):
                n_y = y + dy[i] * k
                n_x = x + dx[i] * k

                if lake[n_y][n_x] == '.':
                    if dist[n_y][n_x] > dist[y][x]+1:
                        dist[n_y][n_x] = dist[y][x] + 1
                        Q.append((n_y,n_x))
                    else:
                        continue

                else:
                    break

    if dist[gy][gx] == INF:
        print('-1')
    else:
        print(dist[gy][gx])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = [list(input()) for _ in range(h)]
# print(x1, y1)
# print(x2, y2)

dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]
MAX = 10**7
dp = [[[(MAX, MAX)] * 4 for _ in range(w)] for _ in range(h)]

q = [((1, 0, x1, y1, i)) for i in range(4)]

while q:
    c1, c2, x, y, d = q.pop()
    # print(x, y, d, c1, c2)
    if c1 > dp[x][y][d][0]:
        continue
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if c[nx][ny] == '@':
            continue
        if i == d and c2 < k:
            if dp[nx][ny][i] > (c1, c2 + 1):
                dp[nx][ny][i] = (c1, c2 + 1)
                q.append(((c1, c2 + 1, nx, ny, i)))
        else:
            if dp[nx][ny][i] > (c1 + 1, 1):
                dp[nx][ny][i] = (c1 + 1, 1)
                q.append(((c1 + 1, 1, nx, ny, i)))

ans = min(dp[x2][y2][i][0] for i in range(4))
if ans == MAX:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = [list(input()) for _ in range(h)]
# print(x1, y1)
# print(x2, y2)

dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]
MAX = 10**7
dp = [[[(MAX, MAX)] * 4 for _ in range(w)] for _ in range(h)]

q = [((1, 0), (x1, y1, i)) for i in range(4)]

while q:
    (c1, c2), (x, y, d) = q.pop()
    # print(x, y, d, c1, c2)
    if c1 > dp[x][y][d][0]:
        continue
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if c[nx][ny] == '@':
            continue
        if i == d and c2 < k:
            if dp[nx][ny][i] > (c1, c2 + 1):
                dp[nx][ny][i] = (c1, c2 + 1)
                q.append(((c1, c2 + 1), (nx, ny, i)))
        else:
            if dp[nx][ny][i] > (c1 + 1, 1):
                dp[nx][ny][i] = (c1 + 1, 1)
                q.append(((c1 + 1, 1), (nx, ny, i)))

ans = min(dp[x2][y2][i][0] for i in range(4))
if ans == MAX:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    lake = [['@' for _ in range(W+2)]]

    for _ in range(H):
        c = ['@'] + list(readline().decode('utf-8').strip()) + ['@']
        lake.append(c)
    lake.append(['@' for _ in range(W+2)])

    dist = [[INF] * (W+2) for _ in range(H+2)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    Q = deque()
    Q.append((sy, sx))
    dist[sy][sx] = 0
    while Q:
        q = Q.popleft()
        y = q[0]
        x = q[1]
        if y == gy and x == gx:
            continue
        for i in range(4):
            for k in range(1,K+1):
                n_y = y + dy[i] * k
                n_x = x + dx[i] * k

                if lake[n_y][n_x] == '.':
                    if dist[n_y][n_x] > dist[y][x]+1:
                        dist[n_y][n_x] = dist[y][x] + 1
                        Q.append((n_y,n_x))
                    else:
                        continue

                else:
                    break

    if dist[gy][gx] == INF:
        print('-1')
    else:
        print(dist[gy][gx])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
import sys

sys.setrecursionlimit(500005)
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

h, w, K = na()
x1, y1, x2, y2 = na()
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1

bd = [ns() for _ in range(h)]

q = []
ds = [9999999999999999] * (h*w*4)

# 0:53
for i in range(4):
    ds[(x1*w+y1)*4+i] = 0
    heappush(q, (ds[(x1*w+y1)*4+i], x1, y1, i))

dr = (1, 0, -1, 0)
dc = (0, 1, 0, -1)
while len(q) > 0:
    d, r, c, di = heappop(q)
    for i in range(4):
        nr, nc = r + dr[i], c + dc[i]
        if 0 <= nr < h and 0 <= nc < w and bd[nr][nc] != "@":
            if di == i:
                nd = d + 1
            else:
                nd = (d + K-1) // K * K + 1
            if nd < ds[(nr*w+nc)*4+i] :
                ds[(nr * w + nc) * 4 + i] = nd
                heappush(q, (nd, nr, nc, i))

ans = min([ds[(x2*w+y2)*4+i] for i in range(4)])
if ans < 999999999999:
    print((ans+K-1)//K)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    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)]

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

    v = set()
    v.add((X1 - 1, Y1 - 1))

    while q:
        c = q.popleft()
        x = c[0]
        y = c[1]
        d = c[2]

        if y == Y2 - 1 and x == X2 - 1:
            print(c[2])
            return

        e, w, n, s = True, True, True, True
        for k in range(1, K + 1):
            if not e and not w and not n and not s:
                break
            if e:
                if y + k >= W or C[x][y + k] == "@":
                    e = False
                else:
                    if (x, y + k) not in v:
                        v.add((x, y + k))
                        q.append((x, y + k, d + 1))
            if w:
                if y - k < 0 or C[x][y - k] == "@":
                    w = False
                else:
                    if (x, y - k) not in v:
                        v.add((x, y - k))
                        q.append((x, y - k, d + 1))

            if n:
                if x - k < 0 or C[x - k][y] == "@":
                    n = False
                else:
                    if (x - k, y) not in v:
                        v.add((x - k, y))
                        q.append((x - k, y, d + 1))

            if s:
                if x + k >= H or C[x + k][y] == "@":
                    s = False
                else:
                    if (x + k, y) not in v:
                        v.add((x + k, y))
                        q.append((x + k, y, d + 1))

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    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)]

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

    v = set()
    v.add((X1 - 1, Y1 - 1))

    while q:
        c = q.popleft()
        x = c[0]
        y = c[1]
        d = c[2]

        if y == Y2 - 1 and x == X2 - 1:
            print(c[2])
            return

        e, w, n, s = True, True, True, True
        for k in range(1, K + 1):
            if not e and not w and not n and not s:
                break
            if e and y + k < W:
                if C[x][y + k] == "@":
                    e = False
                else:
                    if (x, y + k) not in v:
                        v.add((x, y + k))
                        q.append((x, y + k, d + 1))
            if w and y - k >= 0:
                if C[x][y - k] == "@":
                    w = False
                else:
                    if (x, y - k) not in v:
                        v.add((x, y - k))
                        q.append((x, y - k, d + 1))

            if n and x - k >= 0:
                if C[x - k][y] == "@":
                    n = False
                else:
                    if (x - k, y) not in v:
                        v.add((x - k, y))
                        q.append((x - k, y, d + 1))

            if s and x + k < H:
                if C[x + k][y] == "@":
                    s = False
                else:
                    if (x + k, y) not in v:
                        v.add((x + k, y))
                        q.append((x + k, y, d + 1))

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
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

C = [input() for i in range(H)]
dist = [[-1]*W for i in range(H)]
dist[x1][y1] = 0
d = deque([[x1, y1]])
dxy= [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
  x, y = d.popleft()
  if (x, y) == (x2, y2):
    print(dist[x][y])
    quit()
  for dx, dy in dxy:
    xx = x; yy = y
    for i in range(K):
      xx += dx; yy += dy
      if 0<=xx<H and 0<=yy<W and C[xx][yy]!='@':
        if 0 <= dist[xx][yy] <= dist[x][y]:
          break
        dist[xx][yy] = dist[x][y] + 1
        d.append([xx, yy])
      else:
        break

print(dist[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
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

C = [input() for i in range(H)]
dist = [[-1]*W for i in range(H)]
dist[x1][y1] = 0
d = deque([[x1, y1]])
dxy= [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
  x, y = d.popleft()
  for dx, dy in dxy:
    xx = x; yy = y
    for i in range(K):
      xx += dx; yy += dy
      if 0<=xx<H and 0<=yy<W and C[xx][yy]!='@':
        if 0 <= dist[xx][yy] <= dist[x][y]:
          break
        dist[xx][yy] = dist[x][y] + 1
        d.append([xx, yy])
      else:
        break

print(dist[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    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)]

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

    v = set()
    v.add((X1 - 1, Y1 - 1))

    while q:
        c = q.popleft()
        x = c[0]
        y = c[1]
        d = c[2]

        if y == Y2 - 1 and x == X2 - 1:
            print(c[2])
            return

        e, w, n, s = True, True, True, True
        for k in range(1, K + 1):
            if e and y + k < W:
                if C[x][y + k] == "@":
                    e = False
                else:
                    if (x, y + k) not in v:
                        v.add((x, y + k))
                        q.append((x, y + k, d + 1))
            if w and y - k >= 0:
                if C[x][y - k] == "@":
                    w = False
                else:
                    if (x, y - k) not in v:
                        v.add((x, y - k))
                        q.append((x, y - k, d + 1))

            if n and x - k >= 0:
                if C[x - k][y] == "@":
                    n = False
                else:
                    if (x - k, y) not in v:
                        v.add((x - k, y))
                        q.append((x - k, y, d + 1))

            if s and x + k < H:
                if C[x + k][y] == "@":
                    s = False
                else:
                    if (x + k, y) not in v:
                        v.add((x + k, y))
                        q.append((x + k, y, d + 1))

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
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

C = [input() for i in range(H)]
dist = [[-1]*W for i in range(H)]
dist[x1][y1] = 0
d = deque([[x1, y1]])
dxy= [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
  x, y = d.popleft()
  for dx, dy in dxy:
    xx = x; yy = y
    for i in range(K):
      xx += dx; yy += dy
      if 0<=xx<H and 0<=yy<W and C[xx][yy]!='@':
        if 0 <= dist[xx][yy] <= dist[x][y]:
          break
        dist[xx][yy] = dist[x][y] + 1
        d.append([xx, yy])
      else:
        break

print(dist[x2][y2])

Submission status: Time Limit Exceeded

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

H,W,K=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
MAP=[list(input().strip()) for i in range(H)]

for i in range(H):
    for j in range(W):
        if MAP[i][j]==".":
            MAP[i][j]=1<<30
        else:
            MAP[i][j]=-1

Q=deque()
Q.append((x1-1,y1-1))
MAP[x1-1][y1-1]=0

while Q:
    x,y=Q.pop()

    for i in range(1,K+1):
        if 0<=x+i<H and 0<=y<W and (MAP[x+i][y]==1<<30 or MAP[x+i][y]>MAP[x][y]):
            MAP[x+i][y]=MAP[x][y]+1
            Q.appendleft((x+i,y))
        else:
            break

    for i in range(1,K+1):
        if 0<=x-i<H and 0<=y<W and (MAP[x-i][y]==1<<30 or MAP[x-i][y]>MAP[x][y]):
            MAP[x-i][y]=MAP[x][y]+1
            Q.appendleft((x-i,y))
        else:
            break

    for i in range(1,K+1):
        if 0<=x<H and 0<=y+i<W and (MAP[x][y+i]==1<<30 or MAP[x][y+i]>MAP[x][y]):
            MAP[x][y+i]=MAP[x][y]+1
            Q.appendleft((x,y+i))
        else:
            break

    for i in range(1,K+1):
        if 0<=x<H and 0<=y-i<W and (MAP[x][y-i]==1<<30 or MAP[x][y-i]>MAP[x][y]):
            MAP[x][y-i]=MAP[x][y]+1
            Q.appendleft((x,y-i))
        else:
            break
if MAP[x2-1][y2-1]==1<<30:
    print(-1)
else:
    print(MAP[x2-1][y2-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

H,W,K=map(int,input().split())
sy,sx,gy,gx=map(int,input().split())
st=sx+sy*(W+2)
gl=gx+gy*(W+2)
c=['@']*(W+2)
d=[INF]*(W+2)*(H+2)
direction=[[0]*4 for _ in range((H+2)*(W+2))]
d[st]=0
di=(-1,1,W+2,-(W+2))

def main():
    for i in range(H):
        c.extend(['@']+list(input())+['@'])
    c.extend(['@']*(W+2))
    que=deque()
    que.append(st)
    while que:
        v=que.popleft()
        for k in range(4):
            nv=v+di[k]
            if c[nv]=='.':
                if direction[v][k]>0:
                    if d[nv]>d[v]:
                        direction[nv]=[0]*4
                        direction[nv][k]=direction[v][k]-1
                        d[nv]=d[v]
                        que.append(nv)
                    elif d[nv]==d[v]:
                        direction[nv][k]=direction[v][k]-1
                else:
                    if d[nv]>d[v]+1:
                        direction[nv]=[0]*4
                        direction[nv][k]=K-1
                        d[nv]=d[v]+1
                        que.append(nv)
                    elif d[nv]==d[v]+1:
                        direction[nv][k]=K-1
    print(d[gl] if d[gl]!=INF else -1)

if __name__ == "__main__":
    main()