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 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=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost={}
#[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]


# Dijkstra Loop
while True:
  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
    
  #print(q)
  if (len(q) == 0):
    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]
  if place_n == "." or isinstance(place_n, list) and place_n[s_n2] == ".":
    if a < K:
      heappush(q,(c,a+1,s_next))#勢いを１失って、移動
    else:
      heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
    
  #進行方向を変更する場合
  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]] == ".":
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      

#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:
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=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost={}
#[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]


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

#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:
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)]
graph = [["@"]*(W+2)] + [["@"]+list(input())+["@"] for _ in range(H)] + [["@"]*(W+2)]
#はすで囲まれた盤面

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

#or a in graph:
#  print(a)

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

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost={}
#[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]


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

#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:
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)]
graph = [["@"]*(W+2)]
for _ in range(H):
  #graph.append([["@"]*4]+list(map(conv_4, input()))+[["@"]*4])
  graph.append(["@"]+list(input())+["@"])
graph.append(["@"]*(W+2)) #はすで囲まれた盤面
#print(time.time()-it)
#print(graph)

#or a in graph:
#  print(a)

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

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost=[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]


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

#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]

if (xs,ys) == (xg,yg):
  ans = 0
print(ans)

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)]
for _ in range(H):
  graph.append([["@"]*4]+list(map(conv_4, input()))+[["@"]*4])
graph.append([["@"]*4]*(W+2)) #はすで囲まれた盤面
#print(time.time()-it)
#print(graph)

#or a in graph:
#  print(a)

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

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost=[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]


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

#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]

if (xs,ys) == (xg,yg):
  ans = 0
print(ans)

Submission status: Time Limit Exceeded

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

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

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

#グラフを作る　
graph0 = [[["@"]*4]*(W+2)]
graph1 = [[["@"]*4]+ list(map(conv_4, input())) +[["@"]*4] for _ in range(H)]
graph = graph0 + graph1 + graph0 #はすで囲まれた盤面

#or a in graph:
#  print(a)

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

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost=[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

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

#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]

if (xs,ys) == (xg,yg):
  ans = 0

print(ans)

Submission status: Time Limit Exceeded

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

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

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

#グラフを作る　
graph0 = [[["@"]*4]*(W+2)]
graph1 = [[["@"]*4]+ list(map(conv_4, input())) +[["@"]*4] for _ in range(H)]
graph = graph0 + graph1 + graph0 #はすで囲まれた盤面

#or a in graph:
#  print(a)

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

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

#cost=[[[(-1,0)]*4 ]*(W+2) ]*(H+2)
cost=[[[(-1,0) for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

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

#cost 出力
#print(cost[xg][yg])
ans = -1
for i in range(4):
  if ans == -1 and cost[xg][yg][i][0] >= 0:
    ans = cost[xg][yg][i][0]
    #print(ans)
  elif ans >= 0 and 0 <= cost[xg][yg][i][0] < ans:
    ans = cost[xg][yg][i][0]

if (xs,ys) == (xg,yg):
  ans = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase


"""def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)"""

"""def pw(a,b):
    result=1
    while(b>0):
        if(b%2==1): result*=a
        a*=a
        b//=2
    return result"""



def inpt():
    return [int(k) for k in input().split()]


def main():
    n,m,k=map(int,input().split())
    x1,y1,x2,y2=map(int,input().split())
    ar=[]
    ans=[]
    visited=[]
    for i in range(n):
        visited.append([False]*m)
        ar.append(input())
        ans.append([0]*m)

    if(ar[x1-1][y1-1]=='@' or ar[x2-1][y2-1]=='@'):
        print(-1)
    q=[(x1-1,y1-1)]
    br=[(-1,0),(1,0),(0,1),(0,-1)]
    #ar[x1-1][y1-1]=1000000000
    while(q):
        a,b=q.pop(0)
        #print(a,b)
        if(a==x2-1 and b==y2-1):
            print(ans[a][b])
            exit()
        for p,r in br:
            for i in range(1,k+1):
                x=a+i*p
                y=b+i*r
                if not (0<=x<n and 0<=y<m) or ar[x][y]=='@' or (x==x1-1 and y==y1-1):
                    break
                if(0<ans[x][y]<=ans[a][b]):
                    break
                #print('>>>', x, y, ans[x][y])
                ans[x][y]=ans[a][b]+1
                #print('>>>', x, y, ans[x][y])
                if(not visited[x][y]):
                    q.append((x,y))
                    visited[x][y]=True
    print(-1)







BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from heapq import *

# fast input
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 = 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, y2)

    distances = defaultdict(lambda: (INF, 0))
    distances[(start, 0)] = (0, 0)
    shortest_path = {}
    shortest_path[(start, 0)] = None

    leaf = ord("@")

    queue = [((0, 0), (start, 0))]
    DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while queue:
        (d, frac), (frm, direction) = heappop(queue)
        # dp("(frm, direction)", (frm, direction))
        # dp("distances[(frm, direction)]", distances[(frm, direction)])
        if distances[(frm, direction)] < (d, frac):
            # already know shorter path
            continue
        if frm == goal:
            break

        x, y = frm
        # same direction
        # dp("direction", direction)
        dx, dy = DIRS[direction]
        nx = x + dx
        ny = y + dy
        # dp("nx, ny", nx, ny)
        if nx < 1 or H < nx or ny < 1 or W < ny:
            # dp("out of bounds")
            pass
        elif mapdata[nx - 1][ny - 1] == leaf:
            # dp("hit leaf")
            pass
        else:
            if frac == 0:
                newd = d + 1
                newfrac = -K + 1
            else:
                newd = d
                newfrac = frac + 1
            newdist = (newd, newfrac)
            to = ((nx, ny), direction)

            if distances[to] > newdist:
                # found shorter path
                distances[to] = newdist
                heappush(queue, (newdist, to))
                shortest_path[to] = frm

        if direction < 2:
            # facing X axis
            dir = 2
            nx = x
            ny = y + 1
            if W < ny:
                # dp("out of bounds")
                pass
            elif mapdata[nx - 1][ny - 1] == leaf:
                # dp("hit leaf")
                pass
            else:
                newdist = (d + 1, -K + 1)

                to = ((nx, ny), dir)
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = frm

            dir = 3
            nx = x
            ny = y - 1
            if ny < 1:
                # dp("out of bounds")
                pass
            elif mapdata[nx - 1][ny - 1] == leaf:
                # dp("hit leaf")
                pass
            else:
                newdist = (d + 1, -K + 1)

                to = ((nx, ny), dir)
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = frm
        else:
            # facing Y axis
            dir = 0
            nx = x + 1
            ny = y
            if H < nx:
                # dp("out of bounds")
                pass
            elif mapdata[nx - 1][ny - 1] == leaf:
                # dp("hit leaf")
                pass
            else:
                newdist = (d + 1, -K + 1)

                to = ((nx, ny), dir)
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = frm

            dir = 1
            nx = x - 1
            ny = y
            if nx < 1:
                # dp("out of bounds")
                pass
            elif mapdata[nx - 1][ny - 1] == leaf:
                # dp("hit leaf")
                pass
            else:
                newdist = (d + 1, -K + 1)

                to = ((nx, ny), dir)
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = frm

        # dp("distances", distances)

    dist = min(distances[(goal, dir)] for dir in range(4))
    if dist[0] == INF:
        # unreachable
        print(-1)
    else:
        print(dist[0])


main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from heapq import *

# fast input
import sys
input = sys.stdin.buffer.readline
INF = 10 ** 10
# INF = float("inf")

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

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


@profile
def main():
    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, y2)

    distances = defaultdict(lambda: (INF, 0))
    distances[(start, 0)] = (0, 0)
    shortest_path = {}
    shortest_path[(start, 0)] = None

    leaf = ord("@")

    queue = [((0, 0), (start, 0))]
    DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while queue:
        (d, frac), (frm, direction) = heappop(queue)
        # dp("(frm, direction)", (frm, direction))
        # dp("distances[(frm, direction)]", distances[(frm, direction)])
        if distances[(frm, direction)] < (d, frac):
            # already know shorter path
            continue
        if frm == goal:
            break

        x, y = frm
        # same direction
        # dp("direction", direction)
        dx, dy = DIRS[direction]
        nx = x + dx
        ny = y + dy
        if nx < 1 or H < nx or ny < 1 or W < ny:
            # dp("out of bounds")
            pass
        elif mapdata[nx - 1][ny - 1] == leaf:
            # dp("hit leaf")
            pass
        else:
            if frac == 0:
                newd = d + 1
                newfrac = -K + 1
            else:
                newd = d
                newfrac = frac + 1
            newdist = (newd, newfrac)
            to = ((nx, ny), direction)

            if distances[to] > newdist:
                # found shorter path
                distances[to] = newdist
                heappush(queue, (newdist, to))
                shortest_path[to] = frm

        for dir in range(4):
            if dir == direction:
                continue
            # dp("dir", dir)
            dx, dy = DIRS[dir]
            # dp("dx, dy", dx, dy)
            nx = x + dx
            ny = y + dy
            # dp("nx, ny", nx, ny)

            if nx < 1 or H < nx or ny < 1 or W < ny:
                # dp("out of bounds")
                continue
            dp(nx, ny, mapdata[nx - 1][ny - 1])
            if mapdata[nx - 1][ny - 1] == leaf:
                # dp("hit leaf")
                continue
            newdist = (d + 1, -K + 1)

            to = ((nx, ny), dir)
            if distances[to] > newdist:
                # found shorter path
                distances[to] = newdist
                heappush(queue, (newdist, to))
                shortest_path[to] = frm
        # dp("distances", distances)

    dist = min(distances[(goal, dir)] for dir in range(4))
    if dist[0] == INF:
        # unreachable
        print(-1)
    else:
        print(dist[0])

        # path = []
        # cur = goal
        # while True:
        #     frm = shortest_path[cur]
        #     path.append(frm)
        #     cur = frm
        #     if frm == start:
        #         break
        # path.reverse()
        # print(len(path))  # edge count
        # for (frm, to) in path:
        #     print(frm, to)


main()