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 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] <= dp_c + 1:
                    continue

                dp[n_x][n_y] = dp_c + 1

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

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):
    
    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] <= dp_c + 1:
                    continue

                dp[n_x][n_y] = dp_c + 1
                q.append((n_x, n_y))


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

bfs(x1,y1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2][y2] == INF:
    print(-1)
else:
    print(dp[x2][y2])

Submission status: Time Limit Exceeded

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)] for _ in range(H)]

for h in range(H):
    s = sys.stdin.readline()
    for w in range(W):
        if s[w] == "@":
            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):
    
    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 (n_x)<0 or (n_x)>=H or (n_y)<0 or (n_y)>=W:
                    # print("out of range")
                    break

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

                if dp[n_x][n_y] <= dp_c + 1:
                    continue

                dp[n_x][n_y] = dp_c + 1
                q.append((n_x, n_y))


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

# print(x1-1,y1-1)
# print(dp)

bfs(x1-1,y1-1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2 - 1][y2 - 1] == INF:
    print(-1)
else:
    print(dp[x2 - 1][y2 - 1])

Submission status: Time Limit Exceeded

Solution code:
import queue
def solve(s, t):
    global G
    fixed = {}
    q = queue.PriorityQueue()
    q.put((0, s)) # 0は累積コスト
    while q.empty() == False:
        w, x = q.get()
        if w >= INF:
            return w
        if x == t: 
            return w
        if x in fixed: 
            continue;
        fixed[x] = w
        for y in G[x]:
              if y not in fixed:
                    q.put((w + G[x][y], y))
    return None

H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
C = []
for h in range(H):
    c = input()
    C.extend([s for s in c])

INF = 10**9
G = {i:{} for i in range(H*W)}
for h in range(H):
    for w in range(W):
        d = h * W + w
        #print(d)
        if C[d] == '@':
            flag_west = True
            flag_east = True
            flag_north = True
            flag_south = True
        else:
            flag_west = False
            flag_east = False
            flag_north = False
            flag_south = False
        for k in range(1, K+1):
            # west
            pos = d - k
            if h*W <= pos < (h+1)*W:
                #print("\t west: {} {}".format(d - k, C[pos]))
                if C[pos] == '@' or flag_west:
                    G[d][pos] = INF
                    flag_west = True
                else:
                    G[d][pos] = 1
                    
            # east
            pos = d + k
            if h*W <= pos  < (h+1)*W:
                #print("\t east: {} {}".format(d + k, C[pos]))
                if C[pos] == '@' or flag_east:
                    G[d][pos] = INF
                    flag_east = True
                else:
                    G[d][pos] = 1
                    
            # north
            pos = d - k*W
            if 0 <= pos  < H*W:
                #print("\t north: {} {}".format(d - k*W, C[pos]))
                if C[pos] == '@' or flag_north:
                    G[d][pos] = INF
                    flag_north = True
                else:
                    G[d][pos] = 1
                    
            # south
            pos =  d + k*W
            if 0 <= pos  < H*W:
                #print("\t south: {} {}".format(d + k*W, C[pos]))
                if C[pos] == '@' or flag_south:
                    G[d][pos] = INF
                    flag_south = True
                else:
                    G[d][pos] = 1
        
s = W*x1 + y1
t = W*x2 + y2
ans = solve(s, t)
if ans >= INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
def solve(s, t):
    global G
    fixed = {}
    q = queue.PriorityQueue()
    q.put((0, s)) # 0は累積コスト
    while q.empty() == False:
        w, x = q.get()
        if x == t: 
            return w
        if x in fixed: 
            continue;
        fixed[x] = w
        for y in G[x]:
              if y not in fixed:
                    q.put((w + G[x][y], y))
    return None

H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
C = []
for h in range(H):
    c = input()
    C.extend([s for s in c])

INF = 10**9
G = {i:{} for i in range(H*W)}
for h in range(H):
    for w in range(W):
        d = h * W + w
        #print(d)
        if C[d] == '@':
            flag_west = True
            flag_east = True
            flag_north = True
            flag_south = True
        else:
            flag_west = False
            flag_east = False
            flag_north = False
            flag_south = False
        for k in range(1, K+1):
            # west
            pos = d - k
            if h*W <= pos < (h+1)*W:
                #print("\t west: {} {}".format(d - k, C[pos]))
                if C[pos] == '@' or flag_west:
                    G[d][pos] = INF
                    flag_west = True
                else:
                    G[d][pos] = 1
                    
            # east
            pos = d + k
            if h*W <= pos  < (h+1)*W:
                #print("\t east: {} {}".format(d + k, C[pos]))
                if C[pos] == '@' or flag_east:
                    G[d][pos] = INF
                    flag_east = True
                else:
                    G[d][pos] = 1
                    
            # north
            pos = d - k*W
            if 0 <= pos  < H*W:
                #print("\t north: {} {}".format(d - k*W, C[pos]))
                if C[pos] == '@' or flag_north:
                    G[d][pos] = INF
                    flag_north = True
                else:
                    G[d][pos] = 1
                    
            # south
            pos =  d + k*W
            if 0 <= pos  < H*W:
                #print("\t south: {} {}".format(d + k*W, C[pos]))
                if C[pos] == '@' or flag_south:
                    G[d][pos] = INF
                    flag_south = True
                else:
                    G[d][pos] = 1
        
s = W*x1 + y1
t = W*x2 + y2
ans = solve(s, t)
if ans >= INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

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, input().split())
    x1,y1, x2, y2 = map(int, input().split())
    MAP = [['@'] * (W+2)]
    for i in range(H):
        tmp = deque(list(input()))
        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: Time Limit Exceeded

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)] for _ in range(H)]

for h in range(H):
    s = sys.stdin.readline()
    for w in range(W):
        if s[w] == "@":
            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):
    
    q = deque()
    q.append((x1, y1, 0))
    q.append((x1, y1, 1))
    q.append((x1, y1, 2))
    q.append((x1, y1, 3))

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

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

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

            # print(dp_c, (x0+x,y0+y,d), end=" : ")

            if (x0+x)<0 or (x0+x)>=H or (y0+y)<0 or (y0+y)>=W:
                # print("out of range")
                continue

            if dp[x0+x][y0+y] == -1:
                # print("@")
                continue

            # 後ろを向いている場合
            if d % 4 == (d0+2)%4:
                # print("back")
                continue

            # 同方向を向いている場合
            if d % 4 == d0 % 4:
                if dp[x0+x][y0+y] <= dp_c + 1:
                    # print("not update / same d")
                    continue
                else:
                    dp[x0+x][y0+y] = dp_c + 1  # 更新

            # 90°方向を変えた場合
            elif d%4 == (d0+1)%4 or d%4 == (d0+3) % 4:
                if dp[x0+x][y0+y] <= K * math.ceil(dp_c/K) + 1:
                    # print("not update / 90")
                    continue
                else:
                    dp[x0+x][y0+y] = K * math.ceil(dp_c/K) + 1

            q.append((x0+x, y0+y, d))


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

# print(x1-1,y1-1)
# print(dp)

bfs(x1-1,y1-1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2 - 1][y2 - 1] == INF:
    print(-1)
else:
    print(math.ceil(dp[x2 - 1][y2 - 1]/K))

Submission status: Time Limit Exceeded

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]=='@':
                            break
                        elif distance[nx][ny] == INF:
                            d.append((nx, ny))
                            distance[nx][ny] = distance[x][y] + 1

                    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)

Submission status: Time Limit Exceeded

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, input().split())
    x1,y1, x2, y2 = map(int, input().split())
    MAP = []
    for i in range(H):
        MAP.append(input())

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


    checked = [[[0] * 4 for i in range(W)] for _ in range(H)]

    checked[x1-1][y1-1][0] = 1
    checked[x1-1][y1-1][1] = 1
    checked[x1-1][y1-1][2] = 1
    checked[x1-1][y1-1][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) = heappop(queue)
        checked[x-1][y-1][direction] = 1
        if x == x2 and y == y2:
            best_time = time
            break
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if 1 <= n_x <= H and 1 <= n_y <= W and MAP[n_x-1][n_y-1] == '.' and not checked[n_x-1][n_y-1][k]:
                if k == direction:
                    if seq == K:
                        heappush(queue, (time+1, (n_x, n_y, k, 1)))
                    else:
                        heappush(queue, (time, (n_x, n_y, k, seq+1)))
                else:
                    heappush(queue, (time+1, (n_x, n_y, k, 1)))
    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

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, input().split())
    x1,y1, x2, y2 = map(int, input().split())
    MAP = []
    for i in range(H):
        MAP.append(input())

    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)] for _ in range(H)]

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

    command = [(1,0), (0,1), (-1,0), (0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if x == x2 and y == y2 and best_time > time:
            best_time = time
        for k, (i,j) in enumerate(command):
            n_x = x+i
            n_y = y+j
            if 1 <= n_x <= H and 1 <= n_y <= W and MAP[n_x-1][n_y-1] == '.':
                if k == direction and checked[n_x-1][n_y-1][k] > time:
                    if seq == K:
                        checked[n_x-1][n_y-1][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x - 1][n_y - 1][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif checked[n_x-1][n_y-1][k] > time + 1:
                    checked[n_x-1][n_y-1][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: Time Limit Exceeded

Solution code:
import time 
it = time.time()
from heapq import heapify,heappush,heappop

#def conv_4(s):
#  return [s,s,s,s]

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


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

#print(time.time()-it)
#print(graph)

#or a in graph:
#  print(a)

#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
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# fast input
from heapq import heappop, heappush
import sys
input = sys.stdin.buffer.readline
INF = 10 ** 10
# INF = float("inf")

try:
    profile
except:
    def profile(f): return f

DEBUG = True
if DEBUG:
    def dp(*x):  # debugprint
        print(*x)
else:
    def dp(*x): pass


@profile
def main(H, W, K, x1, y1, x2, y2, mapdata):
    # H, W, K = map(int, input().split())
    # x1, y1, x2, y2 = map(int, input().split())
    # mapdata = sys.stdin.buffer.read().splitlines()
    # print(data)
    start = (x1, y1)
    goal = x2 * W + y2

    distances = {}
    # defaultdict(lambda: (INF, 0))
    # distances[(start, 0)] = (0, 0)
    key = (x1 * W + y1) * 5 + 0
    distances[key] = (0, 0)

    shortest_path = {}
    shortest_path[key] = 0

    queue = [((0, 0), key)]
    DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while queue:
        (d, frac), pos_dir = heappop(queue)
        pos, direction = divmod(pos_dir, 5)
        x, y = divmod(pos, W)
        # dp("(frm, direction)", (frm, direction))
        # dp("distances[(frm, direction)]", distances[(frm, direction)])
        dist = distances.get(pos_dir, INF)
        if dist < (d, frac):
            # already know shorter path
            continue
        if pos == goal:
            break

        # same direction
        # dp("direction", direction)
        dx, dy = DIRS[direction]
        nx = x + dx
        ny = y + dy
        # dp("nx, ny", nx, ny)
        if mapdata[nx * W + ny]:
            if frac == 0:
                newd = d + 1
                newfrac = -K + 1
            else:
                newd = d
                newfrac = frac + 1
            newdist = (newd, newfrac)
            to = (nx * W + ny) * 5 + direction

            if distances.get(to, (INF, 0)) > newdist:
                # found shorter path
                distances[to] = newdist
                heappush(queue, (newdist, to))
                shortest_path[to] = pos_dir

        if direction < 2:
            # facing X axis
            dir = 2
            nx = x
            ny = y + 1
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances.get(to, (INF, 0)) > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

            dir = 3
            nx = x
            ny = y - 1
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances.get(to, (INF, 0)) > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir
        else:
            # facing Y axis
            dir = 0
            nx = x + 1
            ny = y
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances.get(to, (INF, 0)) > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

            dir = 1
            nx = x - 1
            ny = y
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances.get(to, (INF, 0)) > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

        # dp("distances", distances)

    dist = min([
        distances.get(goal * 5,  (INF, 0)),
        distances.get(goal * 5 + 1,  (INF, 0)),
        distances.get(goal * 5 + 2,  (INF, 0)),
        distances.get(goal * 5 + 3, (INF, 0)),
    ])
    if dist[0] == INF:
        # unreachable
        print(-1)
    else:
        print(dist[0])


# print(sys.argv)
if sys.argv[-1] == 'ONLINE_JUDGE':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8,i8,i8,i8,i8,i8,b1[:])')(main)
    # b1[:],i8,i8,i8,i8,i8
    cc.compile()
    exit()
else:
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # from my_module import main
    import numpy as np
    C = np.zeros((H + 2, W + 2), np.bool_)
    data = np.frombuffer(
        sys.stdin.buffer.read(),
        'S1')
    # print(data)
    data = data.reshape(H, -1)
    # print(data)
    data = data[:, : W] == b'.'
    # print(data)
    C[1: -1, 1: -1] = data
    C = C.ravel()
    H += 2
    W += 2

    main(H, W, K, x1, y1, x2, y2, C)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
h,w,k = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
grid = [input().rstrip() for i in range(h)]
dp = [[10**6 for i in range(w)] for j in range(h)]
dp[sx-1][sy-1] = 0
q = deque()
q.append((sx-1,sy-1))
while q:
  px,py = q.popleft()
  d = dp[px][py]
  for j in range(1,k+1):
    if px+j >= h or grid[px+j][py] == "@" or dp[px+j][py] <= d:
      break
    dp[px+j][py] = d+1
    q.append((px+j,py))
  for j in range(1,k+1):
    if px-j < 0 or grid[px-j][py] == "@" or dp[px-j][py] <= d:
      break
    dp[px-j][py] = d+1
    q.append((px-j,py))
  for j in range(1,k+1):
    if py+j >= w or grid[px][py+j] == "@" or dp[px][py+j] <= d:
      break 
    dp[px][py+j] = d+1
    q.append((px,py+j))
  for j in range(1,k+1):
    if py-j < 0 or grid[px][py-j] == "@" or dp[px][py-j] <= d:
      break
    dp[px][py-j] = d+1
    q.append((px,py-j))
if dp[gx-1][gy-1] == 10**6:
  print(-1)
else:
  print(dp[gx-1][gy-1])