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:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq

        hq = []
        heapq.heappush(hq, (0, x1, y1, "C", "C"))
        dist = [[INF] * (w + 2) for _ in range(h + 2)]
        dist[x1][y1] = 0
        op = {"N": "S", "S": "N", "E": "W", "W": "E", "C": "X"}

        while hq:
            cost, cx, cy, cd, pd = heapq.heappop(hq)
            new_cost = cost + 1

            for mx, my, md in ((1, 0, "N"), (-1, 0, "S"), (0, 1, "E"), (0, -1, "W")):
                if cd == md:
                    continue
                if op[pd] == md:
                    continue

                for i in range(1, k):
                    nx, ny = cx + mx * i, cy + my * i
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, md, md))
                            dist[nx][ny] = new_cost
                        else:
                            continue
                    else:
                        break
                else:
                    nx, ny = cx + mx * k, cy + my * k
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, "C", md))
                            dist[nx][ny] = new_cost

        return dist[x2][y2]

    ans = bfs()
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq

        hq = []
        heapq.heappush(hq, (0, x1, y1, "C"))
        dist = [[INF] * (w + 2) for _ in range(h + 2)]
        dist[x1][y1] = 0
        op = {"N": "S", "S": "N", "E": "W", "W": "E", "C": "X"}

        while hq:
            cost, cx, cy, cd = heapq.heappop(hq)
            new_cost = cost + 1

            for mx, my, md in ((1, 0, "N"), (-1, 0, "S"), (0, 1, "E"), (0, -1, "W")):
                if cd == md:
                    continue
                if op[cd] == md:
                    continue
                for i in range(1, k):
                    nx, ny = cx + mx * i, cy + my * i
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, md))
                            dist[nx][ny] = new_cost
                        else:
                            continue
                    else:
                        break
                else:
                    nx, ny = cx + mx * k, cy + my * k
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, "C"))
                            dist[nx][ny] = new_cost

        return dist[x2][y2]

    ans = bfs()
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq
        hq = []
        heapq.heappush(hq, (0, x1, y1, "C"))
        dist = [[INF] * (w + 2) for _ in range(h + 2)]
        dist[x1][y1] = 0
        while hq:
            cost, cx, cy, cd = heapq.heappop(hq)
            new_cost = cost + 1

            for mx, my, md in ((1, 0, "N"), (-1, 0, "S"), (0, 1, "E"), (0, -1, "W")):
                if cd == md:
                    continue
                for i in range(1, k):
                    nx, ny = cx + mx * i, cy + my * i
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, md))
                            dist[nx][ny] = new_cost
                        else:
                            continue
                    else:
                        break
                else:
                    nx, ny = cx + mx * k, cy + my * k
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny, "C"))
                            dist[nx][ny] = new_cost

        return dist[x2][y2]

    ans = bfs()
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq
        hq = []
        heapq.heappush(hq, (0, x1, y1))
        dist = [[INF] * (w + 2) for _ in range(h + 2)]
        dist[x1][y1] = 0
        while hq:
            cost, cx, cy = heapq.heappop(hq)
            new_cost = cost + 1

            for mx, my in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                for i in range(1, k + 1):
                    nx, ny = cx + mx * i, cy + my * i
                    if grid[nx][ny] == ".":
                        if new_cost < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny))
                            dist[nx][ny] = new_cost
                        else:
                            continue
                    else:
                        break
        return dist[x2][y2]

    ans = bfs()
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq
        hq = []
        heapq.heappush(hq, (0, x1, y1))
        dist = [[INF] * (w + 2) for _ in range(h + 2)]
        dist[x1][y1] = 0
        while hq:
            cost, cx, cy = heapq.heappop(hq)
            new_cost = cost + 1
            for mx, my in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                for i in range(1, k + 1):
                    nx, ny = cx + mx * i, cy + my * i
                    if grid[nx][ny] == ".":
                        if cost + 1 < dist[nx][ny]:
                            heapq.heappush(hq, (new_cost, nx, ny))
                            dist[nx][ny] = cost + 1
                    else:
                        break
        return dist[x2][y2]

    ans = bfs()
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w,k=map(int,input().split())
sx,sy,gx,gy=map(int,input().split())
sx-=1
sy-=1
gx-=1
gy-=1
c=[]
for i in range(h):
    c.append(input())
    
q=deque([(sx,sy)])
v=[[-1 for j in range(w)] for i in range(h)]
v[sx][sy]=0
f=0
while q:
    x,y=q.popleft()
    for xx,yy in ([1,0],[-1,0],[0,1],[0,-1]):
        nx=x+xx
        ny=y+yy
        if 0<=nx<h and 0<=ny<w and c[nx][ny]=='.' and v[nx][ny]==-1:
            q.append((nx,ny))
            v[nx][ny]=1
            if nx==gx and ny==gy:
                f=1
    if f==1:
        break
if f==0:
    print(-1)
    exit()
q=deque([(sx,sy)])
v=[[-1 for j in range(w)] for i in range(h)]
v[sx][sy]=0
while q:
    x,y=q.popleft()
    cost=v[x][y]
    for xx,yy in ([1,0],[-1,0],[0,1],[0,-1]):
        for i in range(1,k+1):
            nx=x+xx*i
            ny=y+yy*i
            if 0<=nx<h and 0<=ny<w and c[nx][ny]=='.' and (v[nx][ny]==-1 or v[nx][ny]>cost):
                v[nx][ny]=cost+1
                q.append((nx,ny))
                if nx==gx and ny==gy:
                    print(cost+1)
                    exit()
            else:
                break
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w,k=map(int,input().split())
sx,sy,gx,gy=map(int,input().split())
sx-=1
sy-=1
gx-=1
gy-=1
c=[]
for i in range(h):
    c.append(input())
q=deque([(sx,sy)])
v=[[-1 for j in range(w)] for i in range(h)]
v[sx][sy]=0
while q:
    x,y=q.popleft()
    cost=v[x][y]
    for xx,yy in ([1,0],[-1,0],[0,1],[0,-1]):
        for i in range(1,k+1):
            nx=x+xx*i
            ny=y+yy*i
            if 0<=nx<h and 0<=ny<w and c[nx][ny]=='.' and (v[nx][ny]==-1 or v[nx][ny]>cost):
                v[nx][ny]=cost+1
                q.append((nx,ny))
                if nx==gx and ny==gy:
                    print(cost+1)
                    exit()
            else:
                break
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w,k=map(int,input().split())
sx,sy,gx,gy=map(int,input().split())
sx-=1
sy-=1
gx-=1
gy-=1
c=[]
for i in range(h):
    c.append(list(input()))
q=deque([[sx,sy]])
v=[[-1 for j in range(w)] for i in range(h)]
v[sx][sy]=0
while q:
    x,y=q.popleft()
    cost=v[x][y]
    for xx,yy in [[1,0],[-1,0],[0,1],[0,-1]]:
        for i in range(1,k+1):
            nx=x+xx*i
            ny=y+yy*i
            if nx==gx and ny==gy:
                print(cost+1)
                exit()
            if 0<=nx<h and 0<=ny<w and c[nx][ny]=='.' and (v[nx][ny]==-1 or v[nx][ny]>cost):
                v[nx][ny]=cost+1
                q.append([nx,ny])
            else:
                break
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
INF =  float("inf")
import bisect

INF = 10**9

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

def ad_dic():
    ad = defaultdict(lambda: [])
    for i in range(H):
        for j in range(W):
            for k in range(4):
                ad[(i, j, k)].extend([(i,j,(k+1)%4),(i,j,(k+2)%4),(i,j,(k+3)%4)])
            if i != 0:
                if c[i-1][j] == ".":
                    ad[(i,j,0)].append((i-1,j,0))
            if i != H-1:
                if c[i+1][j] == ".":
                    ad[(i,j,1)].append((i+1,j,1))
            if j != 0:
                if c[i][j-1] == ".":
                    ad[(i,j,2)].append((i,j-1,2))
            if j != W-1:
                if c[i][j+1] == ".":
                    ad[(i,j,3)].append((i,j+1,3))

    return ad

ad = ad_dic()

dist = defaultdict(lambda: INF) # 始点から各頂点までの最短距離を格納する
prev = defaultdict(lambda: INF) # 最短経路における，その頂点の前の頂点のIDを格納する

start = (x1-1,y1-1,0)

dist[start] = 0
q = []  # プライオリティキュー．各要素は，(startからある頂点vまでの仮の距離, 頂点vのID)からなるタプル
heapq.heappush(q, (0, start))  # 始点をpush

while len(q) != 0:
    prov_cost, src = heapq.heappop(q)  # pop

    # プライオリティキューに格納されている最短距離が，現在計算できている最短距離より大きければ，distの更新をする必要はない
    if dist[src] < prov_cost:
        continue

    # 他の頂点の探索
    for dest in ad[src]:
        if dest[2] == src[2]:
            if dist[dest] > dist[src] + 1.0/K:
                dist[dest] = dist[src] + 1.0/K  # distの更新
                heapq.heappush(q, (dist[dest], dest))  # キューに新たな仮の距離の情報をpush
                prev[dest] = src  # 前の頂点を記録
        else:
            if dist[dest] > math.ceil(dist[src]):
                dist[dest] = math.ceil(dist[src])
                heapq.heappush(q, (dist[dest], dest))  # キューに新たな仮の距離の情報をpush
                prev[dest] = src  # 前の頂点を記録

# for i in range(H):
#     print([math.ceil(dist[(i,j,0)]) for j in range(W)])

if dist[(x2-1,y2-1,0)] == INF:
    print(-1)
else:
    print(math.ceil(dist[(x2-1,y2-1,0)]))

Submission status: Time Limit Exceeded

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

def arr_4(x):
  return [x,x,x,x]

H, W, K = map(int, input().split())
INF = 10 * H * W

x1, y1, x2, y2 = map(int, input().split())
start = (x1-1 ,y1-1, 0)
goal = (x2-1, y2-1, 0)

G = [list(map(arr_4,input().rstrip())) for _ in range(H)]
#G[i][j][k]: (i,j)座標、k方向(0-3)

def dijkstra(G, start, goal):# G:格子、G[i][j][l] = 0 なら通過可、1ならコスト+1 
  H = len(G)
  W = len(G[0])
  #Dir = 4 方向
  task = [] 
  min_cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  #prev_points = [[[(-2,-2) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  for i in range(4):
    heappush(task, ((1, 0), (start[0], start[1], i), start)) 
    
  #（開始）頂点、コスト、前の点
  # !!コストは（加速回数、慣性で進んだ距離）で規定!! #
  # !!最初の点番号が0でないときは、真ん中の0を変更する!! #
  
  flag = 0
  while task:
    while task:
      c, p, prev = heappop(task)    
      if not G[p[0]][p[1]][p[2]] == "@":
        break  
      if len(task) == 0:
        flag = 1
    if flag == 1:
      break
    #print(task)
    G[p[0]][p[1]][p[2]] = "@"
    min_cost[p[0]][p[1]][p[2]] = c
    #prev_points[p[0]][p[1]] = prev
    
    if p[0] == goal[0] and p[1] == goal[1]:
      return min_cost#, prev_points)
  
    #次の頂点を列挙
    q = []
    if p[0] > 0 and p[2] == 0:#南
      q.append((p[0]-1,p[1],p[2])) 
    if p[0] < H-1 and p[2] == 1:#北
      q.append((p[0]+1,p[1],p[2])) 
    if p[1] > 0 and p[2] == 2:#西
      q.append((p[0],p[1]-1,p[2])) 
    if p[1] < W-1 and p[2] == 3:#東
      q.append((p[0],p[1]+1,p[2]))   
    for i in range(4):
      if not i == p[2]:
        q.append((p[0],p[1],i)) 
    
    for j in q: #制約が入るときはここに追加
      if G[j[0]][j[1]][j[2]] == "@": continue
      
      if p[2] == j[2]:#向き変更なし
        if c[1] == K:
          cost_next = (c[0]+1,1)
        else:
          cost_next = (c[0],c[1]+1)
      else:#向き変更
        cost_next = (c[0]+1,0)
      
      if cost[j[0]][j[1]][j[2]] > cost_next:
        cost[j[0]][j[1]][j[2]] = cost_next
        heappush(task, (cost_next, j, p))
        #print(cost_next, j, p)  
      #print(task)
      
    del q
    
  return min_cost#, prev_points)

min_cost = dijkstra(G, start, goal)

#print(min_cost)

c = min(min_cost[x2-1][y2-1])[0]
if x1 == x2 and y1 == y2:
  c = 0
print(c if c < INF else -1)

Submission status: Time Limit Exceeded

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

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

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


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


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


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

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

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

Submission status: Time Limit Exceeded

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

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

while len(X)>0 and V[gy][gx]==10**10:
  x=X[0]
  y=Y[0]
  X.popleft()
  Y.popleft()
  if D[y][x]==[1,1]:
    continue
  if D[y][x][1]==0:
    i=1
    D[y][x][1]=1
    while G[y][x-i]==".":
      D[y][x-i][1]=1
      if D[y][x-i][0]==0:
        Y.append(y)
        X.append(x-i)
      V[y][x-i]=min(V[y][x-i],V[y][x]+1)
      if i==k:
        D[y][x-i][1]=0
        break
      i=i+1
    i=1
    while G[y][x+i]==".":
      D[y][x+i][1]=1
      if D[y][x+i][0]==0:
        Y.append(y)
        X.append(x+i)
      V[y][x+i]=min(V[y][x+i],V[y][x]+1)
      if i==k:
        D[y][x+i][1]=0
        break
      i=i+1
  if D[y][x][0]==0:
    i=1
    D[y][x][0]=1
    while G[y-i][x]==".":
      D[y-i][x][0]=1
      if D[y-i][x][1]==0:
        Y.append(y-i)
        X.append(x)
      V[y-i][x]=min(V[y-i][x],V[y][x]+1)
      if i==k:
        D[y-i][x][0]=0
        break
      i=i+1
    i=1
    while G[y+i][x]==".":
      D[y+i][x][0]=1
      if D[y+i][x][1]==0:
        Y.append(y+i)
        X.append(x)
      V[y+i][x]=min(V[y+i][x],V[y][x]+1)
      if i==k:
        D[y+1][x][0]=0
        break
      i=i+1
if V[gy][gx]==10**10:
  print(-1)
else:
  print(V[gy][gx])

Submission status: Time Limit Exceeded

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

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

while len(X)>0:
  x=X[0]
  y=Y[0]
  X.popleft()
  Y.popleft()
  if D[y][x]==[1,1]:
    continue
  if D[y][x][1]==0:
    i=1
    D[y][x][1]=1
    while G[y][x-i]==".":
      D[y][x-i][1]=1
      if D[y][x-i][0]==0:
        Y.append(y)
        X.append(x-i)
      V[y][x-i]=min(V[y][x-i],V[y][x]+1)
      if i==k:
        D[y][x-i][1]=0
        break
      i=i+1
    i=1
    while G[y][x+i]==".":
      D[y][x+i][1]=1
      if D[y][x+i][0]==0:
        Y.append(y)
        X.append(x+i)
      V[y][x+i]=min(V[y][x+i],V[y][x]+1)
      if i==k:
        D[y][x+i][1]=0
        break
      i=i+1
  if D[y][x][0]==0:
    i=1
    D[y][x][0]=1
    while G[y-i][x]==".":
      D[y-i][x][0]=1
      if D[y-i][x][1]==0:
        Y.append(y-i)
        X.append(x)
      V[y-i][x]=min(V[y-i][x],V[y][x]+1)
      if i==k:
        D[y-i][x][0]=0
        break
      i=i+1
    i=1
    while G[y+i][x]==".":
      D[y+i][x][0]=1
      if D[y+i][x][1]==0:
        Y.append(y+i)
        X.append(x)
      V[y+i][x]=min(V[y+i][x],V[y][x]+1)
      if i==k:
        D[y+1][x][0]=0
        break
      i=i+1
if V[gy][gx]==10**10:
  print(-1)
else:
  print(V[gy][gx])

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 7
    H, W, K = list(map(int, input().split()))
    X1, Y1, X2, Y2 = list(map(lambda x: int(x) - 1, input().split()))
    C = [input() for _ in range(H)]
    dists = [[INF for _ in range(W)] for _ in range(H)]
    diffs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    cells = [(X2, Y2)]  # goal
    d = 0
    while len(cells) > 0:
        next_cells = list()
        reach_start = False
        for x, y in cells:
            dists[x][y] = d
            if x == X1 and y == Y1:
                reach_start = True
                break
        if reach_start:
            break
        for x, y in cells:
            for dx, dy in diffs:
                next_x, next_y = x, y
                for k in range(1, K + 1):
                    next_x += dx
                    next_y += dy
                    if next_x < 0 or next_x >= H or next_y < 0 or next_y >= W or \
                            dists[next_x][next_y] <= d or C[next_x][next_y] == '@':
                        break
                    next_cells.append((next_x, next_y))
        cells = next_cells
        d += 1
    if dists[X1][Y1] == INF:
        print(-1)
    else:
        print(dists[X1][Y1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 7
    H, W, K = list(map(int, input().split()))
    X1, Y1, X2, Y2 = list(map(lambda x: int(x) - 1, input().split()))
    C = [input() for _ in range(H)]
    dists = [[INF for _ in range(W)] for _ in range(H)]
    cells = [(X2, Y2)]  # goal
    d = 0
    while len(cells) > 0:
        next_cells = list()
        reach_start = False
        for x, y in cells:
            dists[x][y] = d
            if x == X1 and y == Y1:
                reach_start = True
                break
        if reach_start:
            break
        for x, y in cells:
            for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                next_x, next_y = x, y
                for k in range(1, K + 1):
                    next_x += dx
                    next_y += dy
                    if next_x < 0 or next_x >= H or next_y < 0 or next_y >= W or \
                            dists[next_x][next_y] <= d or C[next_x][next_y] == '@':
                        break
                    next_cells.append((next_x, next_y))
        cells = next_cells
        d += 1
    if dists[X1][Y1] == INF:
        print(-1)
    else:
        print(dists[X1][Y1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 7
    H, W, K = list(map(int, input().split()))
    X1, Y1, X2, Y2 = list(map(lambda x: int(x) - 1, input().split()))
    C = [input() for _ in range(H)]
    dists = [[INF for _ in range(W)] for _ in range(H)]
    cells = [(X2, Y2)]  # goal
    d = 0
    while len(cells) > 0:
        next_cells = list()
        reach_start = False
        for x, y in cells:
            dists[x][y] = d
            if x == X1 and y == Y1:
                reach_start = True
                break
        if reach_start:
            break
        for x, y in cells:
            for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                for k in range(1, K + 1):
                    next_x, next_y = x + k * dx, y + k * dy
                    if next_x < 0 or next_x >= H or next_y < 0 or next_y >= W or \
                        C[next_x][next_y] == '@' or dists[next_x][next_y] <= d:
                        break
                    next_cells.append((next_x, next_y))
        cells = next_cells
        d += 1
    if dists[X1][Y1] == INF:
        print(-1)
    else:
        print(dists[X1][Y1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 7
    H, W, K = list(map(int, input().split()))
    X1, Y1, X2, Y2 = list(map(lambda x: int(x) - 1, input().split()))
    C = [input() for _ in range(H)]
    dists = [[INF for _ in range(W)] for _ in range(H)]
    cells = [(0, X2, Y2)]  # goal
    while len(cells) > 0:
        next_cells = list()
        reach_start = False
        for d, x, y in cells:
            dists[x][y] = d
            if x == X1 and y == Y1:
                reach_start = True
                break
        if reach_start:
            break
        for d, x, y in cells:
            for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                for k in range(1, K + 1):
                    next_x, next_y = x + k * dx, y + k * dy
                    if next_x < 0 or next_x >= H or next_y < 0 or next_y >= W or \
                        C[next_x][next_y] == '@' or dists[next_x][next_y] <= d:
                        break
                    next_cells.append((d + 1, next_x, next_y))
        cells = next_cells
    if dists[X1][Y1] == INF:
        print(-1)
    else:
        print(dists[X1][Y1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 7
    H, W, K = list(map(int, input().split()))
    X1, Y1, X2, Y2 = list(map(lambda x: int(x) - 1, input().split()))
    C = [input() for _ in range(H)]
    dists = [[INF for _ in range(W)] for _ in range(H)]
    cells = [(0, X2, Y2)]  # goal
    while len(cells) > 0:
        next_cells = list()
        for d, x, y in cells:
            dists[x][y] = d
        for d, x, y in cells:
            for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                for k in range(1, K + 1):
                    next_x, next_y = x + k * dx, y + k * dy
                    if next_x < 0 or next_x >= H or next_y < 0 or next_y >= W or \
                        C[next_x][next_y] == '@' or dists[next_x][next_y] <= d:
                        break
                    next_cells.append((d + 1, next_x, next_y))
        cells = next_cells
    if dists[X1][Y1] == INF:
        print(-1)
    else:
        print(dists[X1][Y1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
import sys
S=sys.stdin.readlines()
w4x=[1,0,-1,0]
w4y=[0,1,0,-1]
H,W,K=map(int,S[0].split())
x,y,tx,ty=map(int,S[1].split())
C=['@'*(W+2)]
for i in range(H):
  C.append('@')
  C[-1]+=S[i+2]
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)