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 heapq import *
w4x=[1,0,-1,0]
w4y=[0,1,0,-1]
H,W,K=map(int,input().split())
x,y,tx,ty=map(int,input().split())
C=['@'*(W+2)]
for i in range(H):
  C.append('@')
  C[-1]+=input()
  C[-1]+='@'
C.append(C[0])
H,W=H+2,W+2
D=[[[0,0,0,0] for j in range(W)] for i in range(H)]
INF=(10**12)*K
for i in range(H):
  for j in range(W):
    for k in range(4):
      D[i][j][k]=INF
D[x][y][0]=0
Q=[]
heapify(Q)
heappush(Q,(0,(x,y,0)))
a,b,c=0,0,0
while len(Q):
  a=heappop(Q)
  b=a[1]
  if D[b[0]][b[1]][b[2]]<a[0]:
    continue
  c=(b[0]+w4x[b[2]],b[1]+w4y[b[2]],b[2])
  if C[c[0]][c[1]]=='.':
    if D[c[0]][c[1]][c[2]]>D[b[0]][b[1]][b[2]]+1:
      D[c[0]][c[1]][c[2]]=D[b[0]][b[1]][b[2]]+1
      heappush(Q,(D[c[0]][c[1]][c[2]],c))
  for i in range(4):
    if i!=b[2]:
      if D[b[0]][b[1]][i]>((D[b[0]][b[1]][b[2]]+K-1)//K)*K:
        D[b[0]][b[1]][i]=((D[b[0]][b[1]][b[2]]+K-1)//K)*K
        heappush(Q,(D[b[0]][b[1]][i],(b[0],b[1],i)))
if INF==min(D[tx][ty]):
  print(-1)
else:
  print((min(D[tx][ty])+K-1)//K)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
w4x=[1,0,-1,0]
w4y=[0,1,0,-1]
H,W,K=map(int,input().split())
sx,sy,tx,ty=map(int,input().split())
C=['@'*(W+2)]
for i in range(H):
  C.append('@')
  C[-1]+=input()
  C[-1]+='@'
C.append(C[0])
H,W=H+2,W+2
D=[[[0,0,0,0] for j in range(W)] for i in range(H)]
INF=(10**12)*K
def ijk(x,y):
  for i in range(H):
    for j in range(W):
      for k in range(4):
        D[i][j][k]=INF
  D[x][y][0]=0
  Q=[]
  heapify(Q)
  heappush(Q,(0,(x,y,0)))
  a,b,c=0,0,0
  while len(Q):
    a=heappop(Q)
    b=a[1]
    if D[b[0]][b[1]][b[2]]<a[0]:
      continue
    c=(b[0]+w4x[b[2]],b[1]+w4y[b[2]],b[2])
    if C[c[0]][c[1]]=='.':
      if D[c[0]][c[1]][c[2]]>D[b[0]][b[1]][b[2]]+1:
        D[c[0]][c[1]][c[2]]=D[b[0]][b[1]][b[2]]+1
        heappush(Q,(D[c[0]][c[1]][c[2]],c))
    for i in range(4):
      if i!=b[2]:
        if D[b[0]][b[1]][i]>((D[b[0]][b[1]][b[2]]+K-1)//K)*K:
          D[b[0]][b[1]][i]=((D[b[0]][b[1]][b[2]]+K-1)//K)*K
          heappush(Q,(D[b[0]][b[1]][i],(b[0],b[1],i)))

ijk(sx,sy)
if INF==min(D[tx][ty]):
  print(-1)
else:
  print((min(D[tx][ty])+K-1)//K)

Submission status: Time Limit Exceeded

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]=='@':
                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: Time Limit Exceeded

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)
            dist[y+dy][x+dx] = dist[y][x]+1
            q.append((x+dx, y+dy))
print(-1)

Submission status: Time Limit Exceeded

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]:
                    dist[nxt_i][nxt_j] = dist[i][j] + 1
                    q.append((dist[nxt_i][nxt_j], nxt_i, nxt_j))
                else:
                    break
    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: Time Limit Exceeded

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]:
                    dist[nxt_i][nxt_j] = dist[i][j] + 1
                    q.append((d + 1, 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: Time Limit Exceeded

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([(i1, j1)])
    while q:
        i, j = q.popleft()
        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]:
                    dist[nxt_i][nxt_j] = dist[i][j] + 1
                    q.append((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: Time Limit Exceeded

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)] for _ in range(4)]
    dist[R][i1][j1] = 0
    q = deque([(R, i1, j1)])
    while q:
        dire, i, j = q.popleft()

        for cnt in range(1, 4):
            if dist[dire][i][j] < dist[(dire + cnt) % 4][i][j]:
                dist[(dire + cnt) % 4][i][j] = dist[dire][i][j]
                q.appendleft(((dire + cnt) % 4, i, j))

        if dire == U:
            for length in range(1, k + 1):
                nxt_i = i - length
                if 0 <= nxt_i and c[nxt_i][j] == ".":
                    if dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                        dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                        q.append((dire, nxt_i, j))
                else:
                    break
        if dire == D:
            for length in range(1, k + 1):
                nxt_i = i + length
                if nxt_i < h and c[nxt_i][j] == ".":
                    if dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                        dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                        q.append((dire, nxt_i, j))
                else:
                    break
        if dire == L:
            for length in range(1, k + 1):
                nxt_j = j - length
                if 0 <= nxt_j and c[i][nxt_j] == ".":
                    if dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                        dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                        q.append((dire, i, nxt_j))
                else:
                    break
        if dire == R:
            for length in range(1, k + 1):
                nxt_j = j + length
                if nxt_j < w and c[i][nxt_j] == ".":
                    if dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                        dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                        q.append((dire, i, nxt_j))
                else:
                    break

    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 = min([dist[i][x2][y2] for i in range(4)])

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

Submission status: Time Limit Exceeded

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


def dijkstra(i1, j1) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    U, D, L, R = 0, 1, 2, 3
    INF = 10 ** 9
    dist = [[[INF] * w for _ in range(h)] for _ in range(4)]
    dist[U][i1][j1] = 0
    q = [(0, U, i1, j1)]   # q = [(startからの距離, 現在地)]
    while q:
        d, dire, i, j = heapq.heappop(q)
        if dist[dire][i][j] < d:
            continue
        for cnt in range(1, 4):
            if dist[dire][i][j] < dist[(dire + cnt) % 4][i][j]:
                dist[(dire + cnt) % 4][i][j] = dist[dire][i][j]
                heapq.heappush(q, (dist[dire][i][j], (dire + cnt) % 4, i, j))
        if dire == U:
            for length in range(1, k + 1):
                nxt_i = i - length
                if 0 <= nxt_i and c[nxt_i][j] == "." and dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                    dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][nxt_i][j], U, nxt_i, j))
                else:
                    break
        if dire == D:
            for length in range(1, k + 1):
                nxt_i = i + length
                if nxt_i < h and c[nxt_i][j] == "." and dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                    dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][nxt_i][j], D, nxt_i, j))
                else:
                    break
        if dire == L:
            for length in range(1, k + 1):
                nxt_j = j - length
                if 0 <= nxt_j and c[i][nxt_j] == "." and dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                    dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][i][nxt_j], L, i, nxt_j))
                else:
                    break
        if dire == R:
            for length in range(1, k + 1):
                nxt_j = j + length
                if nxt_j < w and c[i][nxt_j] == "." and dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                    dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][i][nxt_j], R, i, nxt_j))
                else:
                    break

    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 = dijkstra(x1, y1)
ans = min([dist[i][x2][y2] for i in range(4)])

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

Submission status: Time Limit Exceeded

Solution code:
import heapq


def dijkstra(i1, j1) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    U, D, L, R = 0, 1, 2, 3
    INF = 10 ** 9
    dist = [[[INF] * w for _ in range(h)] for _ in range(4)]
    dist[U][i1][j1] = 0
    q = [(0, U, i1, j1)]   # q = [(startからの距離, 現在地)]
    while q:
        d, dire, i, j = heapq.heappop(q)
        for cnt in range(1, 4):
            if dist[dire][i][j] < dist[(dire + cnt) % 4][i][j]:
                dist[(dire + cnt) % 4][i][j] = dist[dire][i][j]
                heapq.heappush(q, (dist[dire][i][j], (dire + cnt) % 4, i, j))
        if dist[dire][i][j] < d:
            continue
        if dire == U:
            for length in range(1, k + 1):
                nxt_i = i - length
                if 0 <= nxt_i and c[nxt_i][j] == "." and dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                    dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][nxt_i][j], U, nxt_i, j))
                else:
                    break
        if dire == D:
            for length in range(1, k + 1):
                nxt_i = i + length
                if nxt_i < h and c[nxt_i][j] == "." and dist[dire][i][j] + 1 < dist[dire][nxt_i][j]:
                    dist[dire][nxt_i][j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][nxt_i][j], D, nxt_i, j))
                else:
                    break
        if dire == L:
            for length in range(1, k + 1):
                nxt_j = j - length
                if 0 <= nxt_j and c[i][nxt_j] == "." and dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                    dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][i][nxt_j], L, i, nxt_j))
                else:
                    break
        if dire == R:
            for length in range(1, k + 1):
                nxt_j = j + length
                if nxt_j < w and c[i][nxt_j] == "." and dist[dire][i][j] + 1 < dist[dire][i][nxt_j]:
                    dist[dire][i][nxt_j] = dist[dire][i][j] + 1
                    heapq.heappush(q, (dist[dire][i][nxt_j], R, i, nxt_j))
                else:
                    break

    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 = dijkstra(x1, y1)
ans = min([dist[i][x2][y2] for i in range(4)])

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

Submission status: Time Limit Exceeded

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

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

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

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

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:
                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
                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()

Submission status: Time Limit Exceeded

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:
                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
                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
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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:
                break
            if x == x2 and y == y2:
                if cost < minans:
                    minans = cost
                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
                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
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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")
    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:
                break
            if x == x2 and y == y2:
                if cost < minans:
                    minans = cost
                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
                pond[nx][ny][vec] = ncost
                if nx == x2 and ny == y2:
                    if ncost < minans:
                        minans = ncost
                    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])
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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")
    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:
                break
            if x == x2 and y == y2:
                if cost < minans:
                    minans = cost
                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
                pond[nx][ny][vec] = ncost
                if nx == x2 and ny == y2:
                    if ncost < minans:
                        minans = ncost
                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])
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()