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

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 = [float("inf")] * 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,0)

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

Submission status: Time Limit Exceeded

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,0)

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

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):
            for k in range(4):
                if j!=k:
                    pond.add(4*i+k,4*i+j,0)

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

Solution code:
H,W,K=map(int,input().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() 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):
            for k in range(4):
                if j!=k:
                    pond.add(4*i+k,4*i+j,0)

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: 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
ct = 0
while True:
  it1 = time.time()
  #print(q)
  if (len(q) == 0):
    break#未確定要素がなくなったら終了
  ct+=1
  
  #print(q)
  for _ in range(1,10**9):#未確定の点が取り出されるまで試す
    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
  
  it2 = time.time()
  
  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#到達したら終了
  
  it3 = time.time()
  
  #進行方向に移動する場合
  if s2 == 0:#南向き
    s_next = (s0+1,s1,0)
  elif s2 == 1:#北向き
    s_next = (s0-1,s1,1)
  elif s2 == 2:#東向き
    s_next = (s0,s1+1,2)
  else:#にし向き
    s_next = (s0,s1-1,3)
  it31 = time.time()
  s_n0, s_n1, s_n2 = s_next
  it32 = time.time()
  place_n = graph[s_n0][s_n1]
  #print(s_next)
  #print(place_n)
  it4 = time.time()
  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)
  
  it5 = time.time()
  #it51i = [0 for _ in range(4)]
  #it52i = [0 for _ in range(4)]
  #進行方向を変更する場合
  s_next = (s0,s1,0)
  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)
  it51 = time.time()
  s_next = (s0,s1,1)
  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)
  it52 = time.time()   
  s_next = (s0,s1,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)
  it53 = time.time()      
  s_next = (s0,s1,3)
  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)
  it6 = time.time() 

  """  
  if ct % 10 == 0:
    print(ct)
    print((it2-it1,it3-it2,it4-it3,it5-it4,it6-it5))
    print((it31-it3,it32-it31,it4-it32))
    print((it51-it5,it52-it51,it53-it52,it6-it53))
  """
  
#cost 出力
#print(cost[xg][yg])

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:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

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

INF = 1 << 60
dist = [[[INF] * 2 for _ in range(W)] for _ in range(H)]
dist[x1 - 1][y1 - 1] = [0, 0]

# (cost, x, y, mode)
q = [(0, x1 - 1, y1 - 1, 0), (0, x1 - 1, y1 - 1, 1)]
while q :
  ccost, cx, cy, cmode = heappop(q)
  if ccost > dist[cx][cy][cmode] :
    continue
  for i, (dx, dy) in enumerate(((-1, 0), (0, -1), (1, 0), (0, 1))) :
    nmode = i % 2
    nx, ny = cx + dx, cy + dy
    if cmode == nmode :
      ncost = ccost + 1
      if 0 <= nx < H and 0 <= ny < W and c[nx][ny] != '@' and ncost < dist[nx][ny][nmode] :
        heappush(q, (ncost, nx, ny, nmode))
        dist[nx][ny][nmode] = ncost
  ncost = (ccost + K - 1) // K * K
  if ncost < dist[cx][cy][cmode ^ 1] :
    dist[cx][cy][cmode ^ 1] = ncost
    heappush(q, (ncost, cx, cy, cmode ^ 1))
 
if min(dist[x2 - 1][y2 - 1]) == INF :
  print(-1)
else :
  print((min(dist[x2 - 1][y2 - 1]) + K - 1) // K)

Submission status: Time Limit Exceeded

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

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

dist = [[[float('inf')] * 2 for _ in range(W)] for _ in range(H)]
dist[x1 - 1][y1 - 1] = [0, 0]

# (cost, x, y, mode)
q = [(0, x1 - 1, y1 - 1, 0), (0, x1 - 1, y1 - 1, 1)]
while q :
  ccost, cx, cy, cmode = heappop(q)
  if ccost > dist[cx][cy][cmode] :
    continue
  for i, (dx, dy) in enumerate(((-1, 0), (0, -1), (1, 0), (0, 1))) :
    nmode = i % 2
    nx, ny = cx + dx, cy + dy
    if cmode == nmode :
      ncost = ccost + 1
      if 0 <= nx < H and 0 <= ny < W and c[nx][ny] != '@' and ncost < dist[nx][ny][nmode] :
        heappush(q, (ncost, nx, ny, nmode))
        dist[nx][ny][nmode] = ncost
  ncost = (ccost + K - 1) // K * K
  if ncost < dist[cx][cy][cmode ^ 1] :
    dist[cx][cy][cmode ^ 1] = ncost
    heappush(q, (ncost, cx, cy, cmode ^ 1))
 
if min(dist[x2 - 1][y2 - 1]) == float('inf') :
  print(-1)
else :
  print((min(dist[x2 - 1][y2 - 1]) + K - 1) // K)

Submission status: Time Limit Exceeded

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

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

dist = [[[float('inf')] * 2 for _ in range(W)] for _ in range(H)]
dist[x1 - 1][y1 - 1] = [0, 0]

# (cost, x, y, mode)
q = [(0, x1 - 1, y1 - 1, 0), (0, x1 - 1, y1 - 1, 1)]
while q :
  ccost, cx, cy, cmode = heappop(q)
  if ccost > dist[cx][cy][cmode] :
    continue
  for i, (dx, dy) in enumerate(((-1, 0), (0, -1), (1, 0), (0, 1))) :
    nmode = i % 2
    nx, ny = cx + dx, cy + dy
    if cmode == nmode :
      ncost = ccost + 1
    else :
      ncost = ccost + K - ccost % K
      
    if 0 <= nx < H and 0 <= ny < W and c[nx][ny] != '@' and ncost < dist[nx][ny][nmode] :
      heappush(q, (ncost, nx, ny, nmode))
      dist[nx][ny][nmode] = ncost
 
if min(dist[x2 - 1][y2 - 1]) == float('inf') :
  print(-1)
else :
  print((min(dist[x2 - 1][y2 - 1]) + K - 1) // K)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

read = sys.stdin.read
readline = sys.stdin.readline

h, w, k = map(int, readline().split())
x1, y1, x2, y2 = map(int, readline().split())
x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1

field = [readline() for _ in range(h)]
costs = [[99999999] * w for _ in range(h)]

q = deque([(x1, y1)])
costs[x1][y1] = 0

while q:
    x, y = q.popleft()
    for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        for i in range(1, k + 1):
            px, py = x + dx * i, y + dy * i
            if not(0 <= px < h and 0 <= py < w) or field[px][py] == '@':
                break
            if costs[px][py] < costs[x][y] + 1:
                break
            costs[px][py] = costs[x][y] + 1
            q.append((px, py))

print(-1 if costs[x2][y2] == 99999999 else costs[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

read = sys.stdin.read
readline = sys.stdin.readline

h, w, k = map(int, readline().split())
x1, y1, x2, y2 = map(int, readline().split())
x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1

field = [readline() for _ in range(h)]

visited = [[False] * w for _ in range(h)]
costs = [[-1] * w for _ in range(h)]

q = deque([(x1, y1)])
costs[x1][y1] = 0

while q:
    x, y = q.popleft()
    if visited[x][y]:
        continue
    visited[x][y] = True
    for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        for i in range(1, k + 1):
            px, py = x + dx * i, y + dy * i
            if not(0 <= px < h and 0 <= py < w) or field[px][py] == '@' or visited[px][py]:
                break
            if costs[px][py] == -1 or costs[px][py] > costs[x][y] + 1:
                costs[px][py] = costs[x][y] + 1
                q.append((px, py))

print(costs[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import math
import sys

input = sys.stdin.readline

h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1

field = []
for _ in range(h):
    field.append(list(input()))
visited = [[False for _ in range(w)] for _ in range(h)]
costs = [[99999999 for _ in range(w)] for _ in range(h)]


q = deque([(x1, y1)])
costs[x1][y1] = 0

while q:
    x, y = q.popleft()
    if visited[x][y]:
        continue
    visited[x][y] = True
    for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        for i in range(1, k + 1):
            px, py = x + dx * i, y + dy * i
            if not(0 <= px < h and 0 <= py < w) or field[px][py] == '@' or visited[px][py]:
                break
            if costs[px][py] > costs[x][y] + 1:
                costs[px][py] = costs[x][y] + 1
                q.append((px, py))

print(-1 if costs[x2][y2] == 99999999 else costs[x2][y2])

Submission status: Time Limit Exceeded

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



    if k % 2 == 0 and x1 % 2 == 0:
        # BFS
        # 直線を進めるだけ進む
        from collections import deque
        seen = [[0] * (w+2) for _ in range(h+2)]
        seen[x1][y1] = 1
        todo = deque([(x1, y1)])
 
        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
 
        while len(todo) > 0:
            ix, iy = todo.popleft()
            s = seen[ix][iy] + 1
 
            for j in range(4):
                jx, jy = ix, iy
                dxj, dyj = dx[j], dy[j]
 
                for _ in range(k):
                    jx, jy = jx + dxj, jy + dyj
 
                    if c[jx][jy] == '@':
                        break
 
                    if jx == x2 and jy == y2:
                        print(s - 1)
                        exit()
            
                    if seen[jx][jy] == 0:
                        seen[jx][jy] = s
                        todo.append((jx, jy))



    # Dijkstra
    seen = [[-1] * (w+2) for _ in range(h+2)]
    # todo[i] == (cost, x, y, direction)
    todo = [(0, x1, y1, 0)]
    heapq.heapify(todo)

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

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

        # special case
        if seen[xi][yi] == cost:
            xj, yj = xi + dx[direction], yi + dy[direction]
            if c[xj][yj] == '.' and seen[xj][yj] == -1:
                heapq.heappush(todo, (cost+1, xj, yj, direction))
            continue

        if seen[xi][yi] != -1:
            continue
        seen[xi][yi] = cost

        # goal
        if xi == x2 and yi == y2:
            print((cost-1)//k + 1)
            exit()
        
        # add
        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

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

            if seen[xj][yj] == -1:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    heapq.heappush(todo, (((cost-1)//k + 1)*k + 1, xj, yj, j))

    print(-1)

main()

Submission status: Time Limit Exceeded

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



    if k % 2 == 0:
        # BFS
        # 直線を進めるだけ進む
        from collections import deque
        seen = [[0] * (w+2) for _ in range(h+2)]
        seen[x1][y1] = 1
        todo = deque([(x1, y1)])
 
        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
 
        while len(todo) > 0:
            ix, iy = todo.popleft()
            s = seen[ix][iy] + 1
 
            for j in range(4):
                jx, jy = ix, iy
                dxj, dyj = dx[j], dy[j]
 
                for _ in range(k):
                    jx, jy = jx + dxj, jy + dyj
 
                    if c[jx][jy] == '@':
                        break
 
                    if jx == x2 and jy == y2:
                        print(s - 1)
                        exit()
            
                    if seen[jx][jy] == 0:
                        seen[jx][jy] = s
                        todo.append((jx, jy))



    # Dijkstra
    seen = [[-1] * (w+2) for _ in range(h+2)]
    # todo[i] == (cost, x, y, direction)
    todo = [(0, x1, y1, 0)]
    heapq.heapify(todo)

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

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

        # special case
        if seen[xi][yi] == cost:
            xj, yj = xi + dx[direction], yi + dy[direction]
            if c[xj][yj] == '.' and seen[xj][yj] == -1:
                heapq.heappush(todo, (cost+1, xj, yj, direction))
            continue

        if seen[xi][yi] != -1:
            continue
        seen[xi][yi] = cost

        # goal
        if xi == x2 and yi == y2:
            print((cost-1)//k + 1)
            exit()
        
        # add
        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

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

            if seen[xj][yj] == -1:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    heapq.heappush(todo, (((cost-1)//k + 1)*k + 1, xj, yj, j))

    print(-1)

main()

Submission status: Time Limit Exceeded

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



    if h % 2 == 0:
        # BFS
        # 直線を進めるだけ進む
        from collections import deque
        seen = [[0] * (w+2) for _ in range(h+2)]
        seen[x1][y1] = 1
        todo = deque([(x1, y1)])
 
        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
 
        while len(todo) > 0:
            ix, iy = todo.popleft()
            s = seen[ix][iy] + 1
 
            for j in range(4):
                jx, jy = ix, iy
                dxj, dyj = dx[j], dy[j]
 
                for _ in range(k):
                    jx, jy = jx + dxj, jy + dyj
 
                    if c[jx][jy] == '@':
                        break
 
                    if jx == x2 and jy == y2:
                        print(s - 1)
                        exit()
            
                    if seen[jx][jy] == 0:
                        seen[jx][jy] = s
                        todo.append((jx, jy))



    # Dijkstra
    seen = [[-1] * (w+2) for _ in range(h+2)]
    # todo[i] == (cost, x, y, direction)
    todo = [(0, x1, y1, 0)]
    heapq.heapify(todo)

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

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

        # special case
        if seen[xi][yi] == cost:
            xj, yj = xi + dx[direction], yi + dy[direction]
            if c[xj][yj] == '.' and seen[xj][yj] == -1:
                heapq.heappush(todo, (cost+1, xj, yj, direction))
            continue

        if seen[xi][yi] != -1:
            continue
        seen[xi][yi] = cost

        # goal
        if xi == x2 and yi == y2:
            print((cost-1)//k + 1)
            exit()
        
        # add
        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

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

            if seen[xj][yj] == -1:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    heapq.heappush(todo, (((cost-1)//k + 1)*k + 1, xj, yj, j))

    print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

grid = [None]*h
for i in range(h):
  grid[i] = input()

not_yet = deque([])
already = [[False]*w for _ in range(h)]
dist = [[0]*w for _ in range(h)]

not_yet.append((x1-1, y1-1))
already[x1-1][y1-1] = True

while not_yet:
  key = not_yet.popleft()
  k1, k2 = key[0], key[1]
  
  for i in range(k1-1, max([-1, k1-k-1]), -1):
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
    elif grid[i][k2] == "@":
      break
  for i in range(k1+1, min([h, k1+k+1])):
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
    elif grid[i][k2] == "@":
      break
  for i in range(k2-1, max([-1, k2-k-1]), -1):
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
    elif grid[k1][i] == "@":
      break
  for i in range(k2+1, min([w, k2+k+1])):
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
    elif grid[k1][i] == "@":
      break
      
if dist[x2-1][y2-1] == 0:
  print(-1)
else:
  print(dist[x2-1][y2-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

grid = [None]*h
for i in range(h):
  grid[i] = input()

not_yet = deque([])
already = [[False]*w for _ in range(h)]
dist = [[0]*w for _ in range(h)]

not_yet.append((x1-1, y1-1))
already[x1-1][y1-1] = True

while not_yet:
  key = not_yet.popleft()
  k1, k2 = key[0], key[1]
  
  for i in range(k1-1, max([-1, k1-k-1]), -1):
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
    elif grid[i][k2] == "@":
      break
  for i in range(k1+1, min([h, k1+k+1])):
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
    elif grid[i][k2] == "@":
      break
  for i in range(k2-1, max([-1, k2-k-1]), -1):
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
    elif grid[k1][i] == "@":
      break
  for i in range(k2+1, min([w, k2+k+1])):
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
    elif grid[k1][i] == "@":
      break

if dist[x2-1][y2-1] == 0:
  print(-1)
else:
  print(dist[x2-1][y2-1])

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, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    x1, y1 = x1-1, y1-1
    x2, y2 = x2-1, y2-1
    MAP = str(read()).split('\n')
    #print(MM)
    INF = float('inf')

    queue = []
    for i in range(4):
        heappush(queue, (1, (x1, y1, i, 0)))

    checked = [[INF] * W for _ in range(H)]
    #print(np.array(checked).shape)
    checked[x1][y1] = 0

    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)

        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 0 <= n_x <= H-1 and 0 <= n_y <= W-1 and MAP[n_x][n_y] == '.' and checked[n_x][n_y] >= time:
                if k == direction and seq < K:
                      checked[n_x][n_y] = time
                      heappush(queue, (time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K):
                    if checked[n_x][n_y] >= time + 1:
                        checked[n_x][n_y] = time + 1
                        heappush(queue, (time + 1, (n_x, n_y, k, 1)))

    if best_time == INF:
        print(-1)
    else:
        print(best_time)

if __name__ == "__main__":
    run()