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: Runtime Error

Solution code:
from heapq import heappop, heappush 
def dijkstra(xs, ys, xg, yg,h,w,k,field):
    # que->(cost, x, y)
    que = [(0, xs, ys)]
    inf = 10 ** 6
    dp = [[inf for _ in range(w+1)] for _ in range(h+1)]
    visited = [[False for _ in range(w+1)] for _ in range(h+1)]
    dp[xs][ys] = 0
    dx = [-1,0,1,0]
    dy = [0,1,0,-1]
    while que:
        cost, x, y= heappop(que)
        # 現在のコストより高いなら無視する
        # if cost > dp[x][y]:
        #     continue
        if x == xg and y == yg:
            print(cost)
            exit(0)
        if visited[x][y]
            for i in range(4):
                for j in range(1, k+1):
                    x_, y_ = x+j*dx[i], y+j*dy[i]
                    if not field[x_][y_]:
                        break
                    if dp[x_][y_] > dp[x][y] + 1:
                        dp[x_][y_] = dp[x][y] + 1
                        heappush(que, (dp[x_][y_], x_, y_))
        visited[x][y] = True
    print(-1)
        

def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(int, input().split())
    field = [[False]*(w+2) for _ in range(h+2)]
    for i in range(h):
        # False で覆うことでx,yの制限をなくす。
        s = [True if _ == '.' else False for _ in input()]
        field[i+1] = [False]+s+[False]
    dijkstra(xs, ys, xg, yg, h, w, k, field)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

def main(lines):
    n, m, s = map(int,lines[0].split())
    adj = [[] for _ in range(n)]
    for i in range(m):
        a,b,d = map(int,lines[i+1].split())
        adj[a].append((b,d))
    from heapq import heappush, heappop
    inf = 10**9
    node = []
    dist = [inf]*n
    done = [False]*n
    dist[s] = 0
    heappush(node,(0,s))
    while node:
        cost, v = heappop(node)
        if not done[v]:
            for e in adj[v]:
                if dist[e[0]] > dist[v]+e[1]:
                    dist[e[0]] = dist[v] + e[1]
                    heappush(node, (dist[e[0]],e[0]))
        done[v] = True
    for el in dist:
        if el == inf:
            print('INF') 
        else:
            print(el)       


if __name__ == '__main__':
    lines = []
    for l in sys.stdin:
        lines.append(l.rstrip('\r\n'))
    main(lines)

Submission status: Runtime Error

Solution code:

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
 
    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = input()
        l = ['@']
        for j in i:
            l.append(j)
        l.append('@')
        c.append(l)
    c.append(['@'] * (w+2))
 
    # Dijkstra
    # seen[x][y] = the minimum cost of (x, y)
    # if seen[x][y] == -1, (x, y) is unresearched
    seen = [[-1] * (w+2) for _ in range(h+2)]
 
    # todo[i] == (cost, x, y, direction)
    todo = [(0, x1, y1, 0)]
    heapq.heapify(todo)
 
    # direction
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
 
    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)
 
        # only straight
        if seen[xi][yi] != -1:
            if (seen[xi][yi]+k-1)//k * k > cost:
                xj, yj = xi + dx[direction], yi + dy[direction]
                if c[xj][yj] == '.':
                    heapq.heappush(todo, (cost+1, xj, yj, direction))
            continue
        seen[xi][yi] = cost
 
        # goal
        if xi == x2 and yi == y2:
            print((cost+k-1)//k)
            exit()
        
        # 4 directions
        for j in range(4):
            xj, yj = xi + dx[j], yi + dy[j]
            if c[xj][yj] == '.':
                if j == direction:
                    if seen[xj][yj] == -1 or (seen[xj][yj]+k-1)//k * k > cost:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                elif seen[xj][yj] == -1:
                    heapq.heappush(todo, ((cost+k-1)//k * k + 1, xj, yj, j))
 
    print(-1)
 
main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

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

C = []
for _ in range(H):
    C.append(input())

count_matrix = [[float('inf') for _ in range(W)] for _ in range(H)]


def calc(count, pos, to_dir, move_count):
    if count_matrix[pos["x"]][pos["y"]] <= count:
        return
    
    count_matrix[pos["x"]][pos["y"]] = count
    
    if to_dir == "N" or to_dir == "S":
        if to_dir == "N" and can_move(to_n(pos)):
            if move_count == K:
                count += 1
                move_count = 0
            calc(count, to_n(pos), "N", move_count + 1)
        if to_dir == "S" and can_move(to_s(pos)):
            if move_count == K:
                count += 1
                move_count = 0
            calc(count, to_s(pos), "S", move_count + 1)
        if can_move(to_w(pos)):
            calc(count + 1, to_w(pos), "W", 1)
        if can_move(to_e(pos)):
            calc(count + 1, to_e(pos), "E", 1)
    
    if to_dir == "W" or to_dir == "E":
        if to_dir == "W" and can_move(to_w(pos)):
            if move_count == K:
                count += 1
                move_count = 0
            calc(count, to_w(pos), "W", move_count + 1)
        if to_dir == "E" and can_move(to_e(pos)):
            if move_count == K:
                count += 1
                move_count = 0
            calc(count, to_e(pos), "E", move_count + 1)
        if can_move(to_n(pos)):
            calc(count + 1, to_n(pos), "N", 1)
        if can_move(to_s(pos)):
            calc(count + 1, to_s(pos), "S", 1)
    
    return


def can_move(pos):
    return 0 <= pos["x"] <= H - 1 and 0 <= pos["y"] <= W - 1 and C[pos["x"]][pos["y"]] != "@"


def to_n(pos):
    return {"x": pos["x"] - 1, "y": pos["y"]}


def to_s(pos):
    return {"x": pos["x"] + 1, "y": pos["y"]}


def to_w(pos):
    return {"x": pos["x"], "y": pos["y"] - 1}


def to_e(pos):
    return {"x": pos["x"], "y": pos["y"] + 1}


px = x2 - 1
py = y2 - 1

dest_pos = {"x": px, "y": py}

if can_move(to_n(dest_pos)):
    calc(1, to_n(dest_pos), "N", 1)

if can_move(to_s(dest_pos)):
    calc(1, to_s(dest_pos), "S", 1)

if can_move(to_w(dest_pos)):
    calc(1, to_w(dest_pos), "W", 1)

if can_move(to_e(dest_pos)):
    calc(1, to_e(dest_pos), "E", 1)

ans = count_matrix[x1 - 1][y1 - 1]

print(ans if ans != float('inf') else -1)

Submission status: Runtime Error

Solution code:
import sys

input=sys.stdin.readline

H,W,K=map(int,input().rstrip().split())

class Dijkstra():
    class Edge():
        def __init__(self, _to, _type):
            self.to = _to
            self.type=_type

    def __init__(self, V):
        self.G = [[] for i in range(V)]
        self._E = 0
        self._V = V

    @property
    def E(self):
        return self._E

    @property
    def V(self):
        return self._V

    def add(self, _from, _to, _type):
        self.G[_from].append(self.Edge(_to, _type))
        self._E += 1

    def shortest_path(self, s):
        import heapq
        que = []
        d = [10**18] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e.type==0:
                    if d[e.to] > d[v]-d[v]%K+K*(d[v]%K>0):
                        d[e.to]=d[v]-d[v]%K+K*(d[v]%K>0)
                        heapq.heappush(que,(d[e.to],e.to))
                else:
                    if d[e.to] >d[v]+1:
                        d[e.to]=d[v]+1
                        heapq.heappush(que,(d[e.to],e.to))
        return d

x1,y1,x2,y2=map(int,input().split())
c=[input().rstrip() for i in range(H)]
pond=Dijkstra(4*H*W)
for i in range(H*W):
    h=i//W
    w=i%W
    if c[h][w]==".":
        if h!=0 and c[h-1][w]==".":
            pond.add(4*i,4*(i-W),1)
        if h!=H-1 and c[h+1][w]==".":
            pond.add(4*i+2,4*(i+W)+2,1)
        if w!=0 and c[h][w-1]==".":
            pond.add(4*i+3,4*(i-1)+3,1)
        if w!=W-1 and c[h][w+1]==".":
            pond.add(4*i+1,4*(i+1)+1,1)
        for j in range(4):
            pond.add(4*i+j,4*i+(j+1)%4)

s=W*(x1-1)+y1-1
g=W*(x2-1)+y2-1
ans=pond.shortest_path(4*s)[4*g]
if ans>=10**18:
    print(-1)
else:
    print(ans//K+(ans%K>0))

Submission status: Runtime Error

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print(cost // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        ans = (a+1) * k
                    print(ans//k - 1)
                exit()

    print(-1)

main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
#from functools import lru_cache
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from heapq import heapify,heappush,heappop

def main(H, W, K, xs, ys, xg, yg, graph0):

    #H, W, K = map(int,input().split()) #南北、東西、可動範囲
    #xs, ys, xg, yg = map(int,input().split()) 

    #グラフを作る　
    #graph = [[["@"]*4]*(W+2)]
    at = ["@"]
    ats = ["@" for _ in range(W+2)]
    graph = [at+graph0[i-1]+at if 0 < i < H+1 else ats for i in range(H+2)]
    # + [["@"]+list(input())+["@"] for i in range(H+2)] + [["@"]*(W+2)]
    #はすで囲まれた盤面

    #Dijkstra法による探索  頂点：（座標、向き(s0,n1,e2,w3)）

    q=[]#未確定の頂点を格納しておく。
    cost={}
    tmp={}

    for i in range(4):
    heappush(q,(1,0,(xs,ys,i))) #座標と向き(s0,n1,e2,w3)
    tmp[(xs,ys,i)]=(1,0)

    #print(tmp)
    #cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)

    #[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

    # Dijkstra Loop
    while True:
    #print(q)
    if (len(q) == 0):
        break#未確定要素がなくなったら終了
        
    #print(q)
    while True:#未確定の点が取り出されるまで試す
        if len(q) == 0:
        break
        c, a, s = heappop(q)
        s0, s1, s2 = s
        #print(q,graph[s[0]][s[1]][s[2]])
        place = graph[s0][s1]
        if place == "." or isinstance(place, list) and place[s2] == ".":
        break
        
    cost[s] = (c,a)
    #cost[s[0]][s[1]][s[2]] = (c,a) #確定したコストの値を書き込む
    if place == ".":
        graph[s0][s1] = [".", ".", ".", "."]
    graph[s0][s1][s2] = "@"#確定させる場所にはすを置き、二度と訪れないようにする
    #print((c,a,s))
    #print((s[0],s[1]),(xg,yg))
    if ((s0,s1)==(xg,yg)):
        break#到達したら終了
    
    #進行方向に移動する場合
    if s2 == 0:#南向き
        s_next = (s0+1,s1,0)
    if s2 == 1:#北向き
        s_next = (s0-1,s1,1)
    if s2 == 2:#東向き
        s_next = (s0,s1+1,2)
    if s2 == 3:#にし向き
        s_next = (s0,s1-1,3)
    s_n0, s_n1, s_n2 = s_next
    place_n = graph[s_n0][s_n1]
    #print(s_next)
    #print(place_n)
    if place_n == "." or isinstance(place_n, list) and place_n[s_n2] == ".":
        if a < K:
        if (s_next not in tmp) or tmp[s_next] > (c,a+1):
            #print(tmp,1)
            heappush(q,(c,a+1,s_next))#勢いを１失って、移動
            tmp[s_next]=(c,a+1)
        else:
        if (s_next not in tmp) or tmp[s_next] > (c+1,1):
            #print(tmp,2)
            heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
            tmp[s_next] = (c+1,1)
        
    #進行方向を変更する場合
    for d in range(4):#それぞれの向きについて
        s_next = (s0,s1,d)
        """
        if c > 5:
            print(s_next)
            print(q)
            print(graph[s_next[0]][s_next[1]][s_next[2]])
        """
        if graph[s_next[0]][s_next[1]][s_next[2]] == ".":
        if (s_next not in tmp) or tmp[s_next] > (c+1,0):
            #print(tmp,3)
            heappush(q,(c+1,0,s_next))#再び水を掻く。
            tmp[s_next] = (c+1,0)   

    #cost 出力
    #print(cost[xg][yg])
    """
    ans = -1
    for i in range(4):
    if cost[xg][yg][i] != 0 :
        if ans == -1:
        ans = cost[xg][yg][i][0]
        elif 0 <= cost[xg][yg][i][0] < ans:
        ans = cost[xg][yg][i][0]
    """
    ans = 10**20
    for i in range(4):
    if  (xg,yg,i) in cost:
        ans = min(cost[(xg,yg,i)][0], ans)
    if ans == 10**20:
    ans = -1
    
    if (xs,ys) == (xg,yg):
    ans = 0
    return(ans)

if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i8 = numba.from_dtype(np.int64)
    signature = (i8, i8, i8, i8)
 
    cc = CC('my_module')
    cc.export('main', signature)(main)
    cc.compile()
 
from my_module import main

H, W, K = map(int,input().split()) #南北、東西、可動範囲
xs, ys, xg, yg = map(int,input().split()) 
graph0 = [list(input()) for _ in range(H)]
 
print(main(H, W, K, xs, ys, xg, yg, graph0))

Submission status: Runtime Error

Solution code:
from collections import deque
import sys

N_MAX = 200000 + 5

H, W, K = map(int, input().split())
sth, stw, glh, glw = map(int, input().split())

INF = 10**6 * K

dp = [[INF for _ in range(W + 2)] for _ in range(H + 2)]

dp[0] = [-1] * (W + 2)
dp[H + 1] = [-1] * (W + 2)
for h in range(1, H + 1):
    s = sys.stdin.readline()
    dp[h][0] = -1
    dp[h][W + 1] = -1
    for w in range(1, W + 1):
        if s[w - 1] == "@":
            dp[h][w] = -1

dp[sth][stw] = 0


# Seen = [[INF]*W for _ in range(H)]
XY = {(1, 0), (-1, 0), (0, 1), (0, -1)}


def bfs(sth, stw, glh, glw):
    next_q = deque()
    next_q.append((sth, stw))

    while len(next_q) != 0:
        # キュー取り出し(先頭)
        h, w = next_q.popleft()
        for dh, dw in XY:
            for sk in range(1, K + 1):
                hs, ws = h + dh * sk, w + dw * sk
                if dp[hs][ws] == -1:
                    break
                if dp[hs][ws] == INF:
                    next_q.append((hs, ws))
                    dp[hs][ws] = dp[h][w] + 1
                elif dp[hs][ws] <= dp[h][w]:
                    # もし、dp[hs][ws] が 今の値以下なら
                    # その先はdp[hs][ws]をもとに 書き込まれている or 今後書き込まれる ので止める
                    break
                # if hs == glh and ws == glw:
                #    return dp[h][w] + 1
    # return -1


def main():
    bfs(sth, stw, glh, glw)

    if dp[glh, glw] == INF:
        print(-1)
    else:
        print(dp[glh, glw])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import deque
import math
import sys

N_MAX = 200000 + 5
sys.setrecursionlimit(N_MAX)

H, W, K = map(int, sys.stdin.readline().split())
x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
INF = 10**6 * K

dp = [[INF for _ in range(W+2)] for _ in range(H+2)]

dp[0] = [-1]*(W+2)
dp[H+1] = [-1]*(W+2)
for h in range(1,H+1):
    s = sys.stdin.readline()
    dp[h][0] = -1
    dp[h][W+1] = -1
    for w in range(1,W+1):
        if s[w-1] == "@":
            dp[h][w] = -1

### BFS ###

# ステップ方向
D = [0, 1, 2, 3]  # direction
Y = [1, 0, -1, 0]
X = [0, 1, 0, -1]

def bfs(x1, y1, x2, y2):
    
    q = deque()
    q.append((x1, y1))

    while q:
        # print(q)
        x0, y0 = q.popleft()

        for x, y in zip(X, Y):

            for i in range(1,K+1):

                # print(y0,y,x0,x,d, (y0+y,x0+x,d), end=" : ")
                dp_c = dp[x0][y0]  # 現在のdp値
                n_x, n_y = x0+x*i, y0+y*i

                # print(dp_c, (n_x,n_y), end=" : ")

                if dp[n_x][n_y] == -1:
                    # print("@")
                    break

                if dp[n_x][n_y] == INF:
                    dp[n_x][n_y] = c + 1
                elif dp[n_x][n_y] <= c:
                    break

                if n_x == x2 and n_y == y2:
                    return dp[n_x][n_y]

                q.append((n_x, n_y))

    return -1

# スタート地点を 0 にする
dp[x1][y1] = 0

a = bfs(x1,y1,x2,y2)

print(a)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    MM = str(read()).split('\n')
    #print(MM)
    MAP = [['@'] * (W+2)]
    for s in MM:
        tmp = deque(list(s))
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(list(tmp))
        #print(len(tmp))
    MAP.append(['@'] * (W+2))
    #print(MAP)
    #print(np.array(MAP).shape)




    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+2)] for _ in range(H+2)]
    #print(np.array(checked).shape)
    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > best_time:
            continue
        if x==x2 and y==y2:
            best_time = time
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] >= time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] >= time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))


    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    MM = str(read()).split('\n')
    #print(MM)
    MAP = [['@'] * (W+2)]
    for s in MM:
        tmp = deque(list(s))
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(list(tmp))
        #print(len(tmp))
    MAP.append(['@'] * (W+2))
    #print(MAP)
    #print(np.array(MAP).shape)




    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+2)] for _ in range(H+2)]
    #print(np.array(checked).shape)
    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > best_time:
            continue
        if x==x2 and y==y2:
            best_time = time
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] >= time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] >= time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))


    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    MM = str(read()).split('\n')
    #print(MM)
    MAP = [['@'] * (W+2)]
    for s in MM:
        tmp = deque(list(s))
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(list(tmp))
    MAP.append(['@'] * (W+2))
    #print(MAP)



    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+2)] for _ in range(H+2)]

    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > best_time:
            continue
        if x==x2 and y==y2:
            best_time = time
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] >= time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] >= time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))


    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    MM = read().split('\n')
    MAP = [['@'] * (W+2)]
    for s in MM:
        tmp = deque(list(s))
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(tmp)
    MAP.append(['@'] * (W+2))

    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+2)] for _ in range(H+2)]

    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > best_time:
            continue
        if x==x2 and y==y2:
            best_time = time
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] >= time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] >= time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))


    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque

h,w,k= map(int, input().split())
sx,sy,gx,gy= map(int, input().split())
maze= [list(input()) for i in range(h)]


# 迷路　BFS
def clear_maze(sx, sy, gx, gy):

    INF=-10**9
    distance = [[INF for i in range(w)] for j in range(h)]
    #    distance = [[None]*field_x_length]*field_y_length
    def bfs():
        # きた点と方向を格納
        d=deque
        d.append((sx, sy))
        distance[sx][sy] =0

        while len(d):
            x, y = d.popleft()

            for i in range(0, 4):
                for j in range(1,k+1):
                    nx, ny = x + [j, 0, -j, 0][i], y + [0, j, 0, -j][i]
                    if 0 <= nx < h and 0 <= ny < w:
                        if maze[nx][ny] != '@' and distance[nx][ny] == INF:
                            d.append((nx, ny))
                            distance[nx][ny] = distance[x][y] + 1

                        else:
                            break
                    else:
                        break
                        
        return distance[gx][gy]

    return bfs()

ans=clear_maze(sx-1,sy-1,gx-1,gy-1)

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