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 numpy as np
from collections import deque

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

step_map = np.zeros((H+2, W+2), dtype=np.int)
step_map -= 1

for h in range(H):
    tmp = input()
    for w in range(W):
        if tmp[w] == '.':
            step_map[h+1][w+1] = 0

update_list = deque([(x1, y1)])

while len(update_list) != 0:

    cord = update_list[0]

    x, y = cord[0], cord[1]
    update_list.popleft()
    tmp_step = step_map[x][y]

    # up
    for i in range(1, K+1, 1):
        if step_map[x-i][y] != 0 and step_map[x-i][y] != tmp_step + 1:
            break
        step_map[x-i][y] = step_map[x][y] + 1
        update_list.append((x-i, y))

    # down
    for i in range(1, K + 1, 1):
        if step_map[x + i][y] != 0 and step_map[x + i][y] != tmp_step + 1:
            break
        step_map[x + i][y] = step_map[x][y] + 1
        update_list.append((x + i, y))

    # left
    for i in range(1, K + 1, 1):
        if step_map[x][y - i] != 0 and step_map[x][y - i] != tmp_step + 1:
            break
        step_map[x][y - i] = step_map[x][y] + 1
        update_list.append((x, y - i))

    # right
    for i in range(1, K + 1, 1):
        if step_map[x][y + i] != 0 and step_map[x][y + i] != tmp_step + 1:
            break
        step_map[x][y + i] = step_map[x][y] + 1
        update_list.append((x, y + i))

    if step_map[x2][y2] != 0:
        print(step_map[x2][y2])
        exit()


print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from heapq import heapify,heappush,heappop
dt = ord(".")
at = ord("@")

def conv_4(s):
  return [ord(s)]*4

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

xs -= 1
ys -= 1
xg -= 1
yg -= 1

#print(time.time()-it)
#グラフを作る　
graph = [list(map(conv_4,input())) for _ in range(H)]

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

q=[]#未確定の頂点を格納しておく。
cost=[[[0 for _ in range(4)] for _ in range(W)] for _ in range(H)]
tmp=[[[(10**15,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]

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

# Dijkstra Loop
ct = 0
while q:
  #it1 = time.time()
  #print(q)
  ct+=1  
  while q:#未確定の点が取り出されるまで試す
    c, a, s = heappop(q)
    s0, s1, s2 = s
    if graph[s0][s1][s2] == dt:
      break

  cost[s0][s1][s2] = (c,a) #確定したコストの値を書き込む
  graph[s0][s1][s2] = at #確定させる場所にはすを置き、二度と訪れないようにする

  if (s0 == xg and s1 == yg):
    break#到達したら終了
  
  #it3 = time.time()
  
  #進行方向に移動する場合
  if s2 == 0 and s0 < H-1:#南向き
    s_next = (s0+1,s1,0)
    flag = 1
  elif s2 == 1 and s0 > 0:#北向き
    s_next = (s0-1,s1,1)
    flag = 1
  elif s2 == 2 and s1 < W-1:#東向き
    s_next = (s0,s1+1,2)
    flag = 1
  elif s2 == 3 and s1 > 0:#にし向き
    s_next = (s0,s1-1,3)
    flag = 1
  else : 
    flag = 0
  #it31 = time.time()
  if flag == 1:
    s_n0, s_n1, s_n2 = s_next
    #print(s_next)
  
    if graph[s_n0][s_n1][s_n2] == dt:
      if a < K:
        if tmp[s_n0][s_n1][s_n2] > (c,a+1):
          heappush(q,(c,a+1,s_next))#勢いを１失って、移動
          tmp[s_n0][s_n1][s_n2] = (c,a+1)
      else:
        if tmp[s_n0][s_n1][s_n2] > (c+1,1):
          heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
          tmp[s_n0][s_n1][s_n2] = (c+1,1)
  
  #進行方向を変更する場合
  for i in range(1,4):
    if graph[s0][s1][(s2+i)%4] == dt:
      if tmp[s0][s1][(s2+i)%4] > (c+1,0):
        heappush(q,(c+1,0,(s0,s1,(s2+i)%4)))#再び水を掻く。
        tmp[s0][s1][(s2+i)%4] = (c+1,0)

ans = 10**20
for i in range(4):
  if  cost[xg][yg][i] == 0:
    cost[xg][yg][i] = (10**15, 0)
  ans = min(cost[xg][yg][i][0], ans)
if ans == 10**15:
  ans = -1
  
if (xs,ys) == (xg,yg):
  ans = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from heapq import heapify,heappush,heappop
dt = ord(".")
at = ord("@")

def conv_4(s):
  return [ord(s)]*4

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

xs -= 1
ys -= 1
xg -= 1
yg -= 1

#print(time.time()-it)
#グラフを作る　
graph = [list(map(conv_4,input())) for _ in range(H)]

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

q=[]#未確定の頂点を格納しておく。
cost=[[[0 for _ in range(4)] for _ in range(W)] for _ in range(H)]
tmp=[[[(10**15,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]

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

# Dijkstra Loop
ct = 0
while q:
  #it1 = time.time()
  #print(q)
  ct+=1  
  while q:#未確定の点が取り出されるまで試す
    c, a, s = heappop(q)
    s0, s1, s2 = s
    if graph[s0][s1][s2] == dt:
      break

  cost[s0][s1][s2] = (c,a) #確定したコストの値を書き込む
  graph[s0][s1][s2] = at #確定させる場所にはすを置き、二度と訪れないようにする

  if ((s0,s1)==(xg,yg)):
    break#到達したら終了
  
  #it3 = time.time()
  
  #進行方向に移動する場合
  if s2 == 0 and s0 < H-1:#南向き
    s_next = (s0+1,s1,0)
    flag = 1
  elif s2 == 1 and s0 > 0:#北向き
    s_next = (s0-1,s1,1)
    flag = 1
  elif s2 == 2 and s1 < W-1:#東向き
    s_next = (s0,s1+1,2)
    flag = 1
  elif s2 == 3 and s1 > 0:#にし向き
    s_next = (s0,s1-1,3)
    flag = 1
  else : 
    flag = 0
  #it31 = time.time()
  if flag == 1:
    s_n0, s_n1, s_n2 = s_next
    #print(s_next)
  
    if graph[s_n0][s_n1][s_n2] == dt:
      if a < K:
        if tmp[s_n0][s_n1][s_n2] > (c,a+1):
          heappush(q,(c,a+1,s_next))#勢いを１失って、移動
          tmp[s_n0][s_n1][s_n2] = (c,a+1)
      else:
        if tmp[s_n0][s_n1][s_n2] > (c+1,1):
          heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
          tmp[s_n0][s_n1][s_n2] = (c+1,1)
  
  #進行方向を変更する場合
  s_next = (s0,s1,0)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it51 = time.time()
  
  s_next = (s0,s1,1)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it52 = time.time()  
  
  s_next = (s0,s1,2)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it53 = time.time()  
  
  s_next = (s0,s1,3)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)

ans = 10**20
for i in range(4):
  if  cost[xg][yg][i] == 0:
    cost[xg][yg][i] = (10**15, 0)
  ans = min(cost[xg][yg][i][0], ans)
if ans == 10**15:
  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
dt = ord(".")
at = ord("@")

def conv_4(s):
  return [ord(s)]*4

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

xs -= 1
ys -= 1
xg -= 1
yg -= 1

#print(time.time()-it)
#グラフを作る　
graph = [list(map(conv_4,input())) for _ in range(H)]

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

q=[]#未確定の頂点を格納しておく。
cost=[[[0 for _ in range(4)] for _ in range(W)] for _ in range(H)]
tmp=[[[(10**15,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]

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

# Dijkstra Loop
ct = 0
while q:
  #it1 = time.time()
  #print(q)
  ct+=1  
  while q:#未確定の点が取り出されるまで試す
    c, a, s = heappop(q)
    s0, s1, s2 = s
    if graph[s0][s1][s2] == dt:
      break

  cost[s0][s1][s2] = (c,a) #確定したコストの値を書き込む
  graph[s0][s1][s2] = at #確定させる場所にはすを置き、二度と訪れないようにする

  if ((s0,s1)==(xg,yg)):
    break#到達したら終了
  
  #it3 = time.time()
  
  #進行方向に移動する場合
  if s2 == 0 and s0 < H-1:#南向き
    s_next = (s0+1,s1,0)
    flag = 1
  elif s2 == 1 and s0 > 0:#北向き
    s_next = (s0-1,s1,1)
    flag = 1
  elif s2 == 2 and s1 < W-1:#東向き
    s_next = (s0,s1+1,2)
    flag = 1
  elif s2 == 3 and s1 > 0:#にし向き
    s_next = (s0,s1-1,3)
    flag = 1
  else : 
    flag = 0
  #it31 = time.time()
  if flag == 1:
    s_n0, s_n1, s_n2 = s_next
    #print(s_next)
  
    if graph[s_n0][s_n1][s_n2] == dt:
      if a < K:
        if tmp[s_n0][s_n1][s_n2] > (c,a+1):
          heappush(q,(c,a+1,s_next))#勢いを１失って、移動
          tmp[s_n0][s_n1][s_n2] = (c,a+1)
      else:
        if tmp[s_n0][s_n1][s_n2] > (c+1,1):
          heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
          tmp[s_n0][s_n1][s_n2] = (c+1,1)
  
  #進行方向を変更する場合
  s_next = (s0,s1,0)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it51 = time.time()
  
  s_next = (s0,s1,1)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it52 = time.time()  
  
  s_next = (s0,s1,2)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it53 = time.time()  
  
  s_next = (s0,s1,3)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)

ans = 10**20
for i in range(4):
  if  cost[xg][yg][i] == 0:
    cost[xg][yg][i] = (10**15, 0)
  ans = min(cost[xg][yg][i][0], ans)
if ans == 10**15:
  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
dt = ord(".")
at = ord("@")
#def conv_4(s):
#  return [s,s,s,s]

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

xs -= 1
ys -= 1
xg -= 1
yg -= 1

#print(time.time()-it)
#グラフを作る　
graph = [list(map(ord,input())) for _ in range(H)]

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

q=[]#未確定の頂点を格納しておく。
cost=[[[0 for _ in range(4)] for _ in range(W)] for _ in range(H)]
tmp=[[[(10**15,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]

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

# Dijkstra Loop
ct = 0
while q:
  #it1 = time.time()
  #print(q)
  ct+=1  
  while q:#未確定の点が取り出されるまで試す
    c, a, s = heappop(q)
    s0, s1, s2 = s
    place = graph[s0][s1]
    if place == dt or isinstance(place, list) and place[s2] == dt:
      break

  cost[s0][s1][s2] = (c,a) #確定したコストの値を書き込む
  if place == dt:
    graph[s0][s1] = [dt]*4
  graph[s0][s1][s2] = at #確定させる場所にはすを置き、二度と訪れないようにする
  #if ct >70:
  #  print((c,a,s))
  #print((s[0],s[1]),(xg,yg))
  if ((s0,s1)==(xg,yg)):
    break#到達したら終了
  
  #it3 = time.time()
  
  #進行方向に移動する場合
  if s2 == 0 and s0 < H-1:#南向き
    s_next = (s0+1,s1,0)
    flag = 1
  elif s2 == 1 and s0 > 0:#北向き
    s_next = (s0-1,s1,1)
    flag = 1
  elif s2 == 2 and s1 < W-1:#東向き
    s_next = (s0,s1+1,2)
    flag = 1
  elif s2 == 3 and s1 > 0:#にし向き
    s_next = (s0,s1-1,3)
    flag = 1
  else : 
    flag = 0
  #it31 = time.time()
  if flag == 1:
    s_n0, s_n1, s_n2 = s_next
    #print(s_next)
    place_n = graph[s_n0][s_n1]
  
    if place_n == dt or isinstance(place_n, list) and place_n[s_n2] == dt:
      if a < K:
        if tmp[s_n0][s_n1][s_n2] > (c,a+1):
          heappush(q,(c,a+1,s_next))#勢いを１失って、移動
          tmp[s_n0][s_n1][s_n2]=(c,a+1)
      else:
        if tmp[s_n0][s_n1][s_n2] > (c+1,1):
          heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
          tmp[s_n0][s_n1][s_n2] = (c+1,1)
  
  #進行方向を変更する場合
  s_next = (s0,s1,0)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it51 = time.time()
  
  s_next = (s0,s1,1)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it52 = time.time()  
  
  s_next = (s0,s1,2)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it53 = time.time()  
  
  s_next = (s0,s1,3)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == dt:
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (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  cost[xg][yg][i] == 0:
    cost[xg][yg][i] = (10**15, 0)
  ans = min(cost[xg][yg][i][0], ans)
if ans == 10**15:
  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=[]#未確定の頂点を格納しておく。
cost=[[[0 for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]
tmp=[[[(10**15,0) for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

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**15):#未確定の点が取り出されるまで試す
    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[s0][s1][s2] = (c,a)
  #cost[s[0]][s[1]][s[2]] = (c,a) #確定したコストの値を書き込む
  if place == ".":
    graph[s0][s1] = [".", ".", ".", "."]
  graph[s0][s1][s2] = "@"#確定させる場所にはすを置き、二度と訪れないようにする
  #if ct >70:
  #  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 tmp[s_n0][s_n1][s_n2] > (c,a+1):
        #print(tmp,1)
        heappush(q,(c,a+1,s_next))#勢いを１失って、移動
        tmp[s_n0][s_n1][s_n2]=(c,a+1)
    else:
      if tmp[s_n0][s_n1][s_n2] > (c+1,1):
        #print(tmp,2)
        heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
        tmp[s_n0][s_n1][s_n2] = (c+1,1)
  
  #it5 = time.time()
  #it51i = [0 for _ in range(4)]
  #it52i = [0 for _ in range(4)]
  
  #進行方向を変更する場合
  s_next = (s0,s1,0)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == ".":
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it51 = time.time()
  
  s_next = (s0,s1,1)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == ".":
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it52 = time.time()  
  
  s_next = (s0,s1,2)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == ".":
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (c+1,0)
  #it53 = time.time()  
  
  s_next = (s0,s1,3)
  s_n0, s_n1, s_n2 = s_next
  place_direct = graph[s_n0][s_n1][s_n2]
  if place_direct == ".":
    if tmp[s_n0][s_n1][s_n2] > (c+1,0):
      heappush(q,(c+1,0,s_next))#再び水を掻く。
      tmp[s_n0][s_n1][s_n2] = (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  cost[xg][yg][i] == 0:
    cost[xg][yg][i] = (10**15, 0)
  ans = min(cost[xg][yg][i][0], ans)
if ans == 10**15:
  ans = -1
  
if (xs,ys) == (xg,yg):
  ans = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

step_map = np.zeros((H+2, W+2), dtype=np.int)
step_map -= 1

for h in range(H):
    tmp = input()
    for w in range(W):
        if tmp[w] == '.':
            step_map[h+1][w+1] = 0

update_list = [(x1, y1)]

while len(update_list) != 0:
    tmp_list = []
    for cord in update_list:
        x, y = cord[0], cord[1]
        tmp_step = step_map[x][y]

        # up
        for i in range(1, K+1, 1):
            if step_map[x-i][y] != 0 and step_map[x-i][y] != tmp_step + 1:
                break
            step_map[x-i][y] = step_map[x][y] + 1
            tmp_list.append((x-i, y))

        # down
        for i in range(1, K + 1, 1):
            if step_map[x + i][y] != 0 and step_map[x + i][y] != tmp_step + 1:
                break
            step_map[x + i][y] = step_map[x][y] + 1
            tmp_list.append((x + i, y))

        # left
        for i in range(1, K + 1, 1):
            if step_map[x][y - i] != 0 and step_map[x][y - i] != tmp_step + 1:
                break
            step_map[x][y - i] = step_map[x][y] + 1
            tmp_list.append((x, y - i))

        # right
        for i in range(1, K + 1, 1):
            if step_map[x][y + i] != 0 and step_map[x][y + i] != tmp_step + 1:
                break
            step_map[x][y + i] = step_map[x][y] + 1
            tmp_list.append((x, y + i))

        if step_map[x2][y2] != 0:
            print(step_map[x2][y2])
            exit()

        update_list = tmp_list


print(-1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

step_map = np.zeros((H+2, W+2), dtype=np.int)
step_map -= 1

for h in range(H):
    tmp = input()
    for w in range(W):
        if tmp[w] == '.':
            step_map[h+1][w+1] = 0

update_list = [(x1, y1)]

while len(update_list) != 0:
    tmp_list = []
    for cord in update_list:
        x, y = cord[0], cord[1]
        tmp_step = step_map[x][y]

        # up
        for i in range(1, K+1, 1):
            if step_map[x-i][y] != 0 and step_map[x-i][y] != tmp_step + 1:
                break
            step_map[x-i][y] = step_map[x][y] + 1
            tmp_list.append((x-i, y))

        # down
        for i in range(1, K + 1, 1):
            if step_map[x + i][y] != 0 and step_map[x + i][y] != tmp_step + 1:
                break
            step_map[x + i][y] = step_map[x][y] + 1
            tmp_list.append((x + i, y))

        # left
        for i in range(1, K + 1, 1):
            if step_map[x][y - i] != 0 and step_map[x][y - i] != tmp_step + 1:
                break
            step_map[x][y - i] = step_map[x][y] + 1
            tmp_list.append((x, y - i))

        # right
        for i in range(1, K + 1, 1):
            if step_map[x][y + i] != 0 and step_map[x][y + i] != tmp_step + 1:
                break
            step_map[x][y + i] = step_map[x][y] + 1
            tmp_list.append((x, y + i))

        if step_map[x1][y1] == 0:
            step_map[x1][y1] = 1

        if step_map[x2][y2] != 0:
            print(step_map[x2][y2])
            exit()

        update_list = tmp_list


print(-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from heapq import heappush, heappop, heapify
sys.setrecursionlimit(10**8)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]


INF = float("inf")
MOD = 10**9 + 7

def array(*args, initial=0):
    pre = "[" * len(args)
    post = ""
    for a in args[::-1]:
        post += " for _ in range(" + str(a) + ")]"
    S = pre + "{}".format(initial) + post
    return eval(S)


def main():
    H, W, K = MAP()
    x1, y1, x2, y2 = MAP()
    # 空間はINF,壁は-1, →↑←↓
    pond = array(H + 2, W + 2, 4, initial=-1)
    for h in range(1, H + 1):
        for w, c in enumerate(input(), start=1):
            if c == ".":
                for i in range(4):
                    pond[h][w][i] = INF
    q = []
    # 距離(), x, y, 方向
    heappush(q, ((0, 0), x1, y1, 0))
    heappush(q, ((0, 0), x1, y1, 1))
    heappush(q, ((0, 0), x1, y1, 2))
    heappush(q, ((0, 0), x1, y1, 3))
    DX = (1, 0, -1, 0)
    DY = (0, 1, 0, -1)
    while q:
        (a0, a1), x, y, d = heappop(q)
        # 順方向へ進む
        nx = x + DX[d]
        ny = y + DY[d]
        # print((a0, a1), x, y, d, nx, ny)
        if pond[nx][ny][0] == -1:     # 行き止まりなら何もせず
            continue
        if pond[nx][ny][(d + 1) % 4] > a0 + 1:
            pond[nx][ny][(d + 1) % 4] = a0 + 1
            heappush(q, ((a0 + 1, 0), nx, ny, (d + 1) % 4))
        if pond[nx][ny][(d - 1) % 4] > a0 + 1:
            pond[nx][ny][(d - 1) % 4] = a0 + 1
            heappush(q, ((a0 + 1, 0), nx, ny, (d - 1) % 4))
        if pond[nx][ny][d] >= a0 + 1:
            pond[nx][ny][d] = a0 + 1
            if a1 + 1 < K:
                heappush(q, ((a0, a1 + 1), nx, ny, d))
            else:
                heappush(q, ((a0 + 1, 0), nx, ny, d))
        if (nx, ny) == (x2, y2):
            print(a0 + 1)
            return
    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from heapq import heappush, heappop, heapify
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]

def main():
    H, W, K = MAP()
    HH = max(H, W) + 2
    x1, y1, x2, y2 = LIST()
    c = [[-1] + [0 if c == "." else -1 for c in input()] + [-1]
         for i in range(H)]
    c = [[-1] * (W + 2)] + c + [[-1] * (W + 2)]

    # 0123: 上下左右
    stack = []
    heappush(stack, (0, x1, y1, 0))
    heappush(stack, (0, x1, y1, 1))
    heappush(stack, (0, x1, y1, 2))
    heappush(stack, (0, x1, y1, 3))
    DX = (1, 0, -1, 0)
    DY = (0, 1, 0, -1)
    while stack:
        curr, x, y, d = heappop(stack)
        flag = True
        a = curr + 1
        for k in range(1, K + 1):
            xx, yy = x + k * DX[d], y + k * DY[d]
            if c[xx][yy] == 0:
                b = c[xx + DX[(d - 1) % 4]][yy + DY[(d - 1) % 4]]
                if b == 0 or b == a + 1:
                    heappush(stack, (a, xx, yy, (d - 1) % 4))
                b = c[xx + DX[(d + 1) % 4]][yy + DY[(d + 1) % 4]]
                if b == 0 or b == a + 1:
                    heappush(stack, (a, xx, yy, (d + 1) % 4))
                c[xx][yy] = a
            elif c[xx][yy] != a:
                flag = False
                break
        if flag:
            heappush(stack, (a, xx, yy, d))
        if c[x2][y2] > 0:
            print(c[x2][y2])
            return

    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]


INF = float("inf")
MOD = 10**9 + 7
EPS = 1e-6
KETA = 10**7


def main():
    H, W, K = MAP()
    x1, y1, x2, y2 = LIST()
    c = [[-1] + [0 if c == "." else -1 for c in input()] + [-1]
         for i in range(H)]
    c = [[-1] * (W + 2)] + c + [[-1] * (W + 2)]
    c[x1][y1] = 0

    # 0123: 上下左右
    stack = [((x1 * KETA + y1) << 2) + 0, ((x1 * KETA + y1) << 2) + 1,
             ((x1 * KETA + y1) << 2) + 2, ((x1 * KETA + y1) << 2) + 3]
    DX = (1, 0, -1, 0)
    DY = (0, 1, 0, -1)
    head = 0
    while head < len(stack):
        b = stack[head]
        head += 1
        d = b % 4
        x, y = divmod(b >> 2, KETA)
        flag = True
        a = c[x][y] + 1
        for k in range(1, K + 1):
            xx, yy = x + k * DX[d], y + k * DY[d]
            if c[xx][yy] != 0 and c[xx][yy] != a:
                flag = False
                break
            stack.append(((xx * KETA + yy) << 2) + (d - 1) % 4)
            stack.append(((xx * KETA + yy) << 2) + (d + 1) % 4)
            c[xx][yy] = a
        if flag:
            stack.append(((xx * KETA + yy) << 2) + d)
        if c[x2][y2] > 0:
            print(c[x2][y2])
            return

    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]


INF = float("inf")
MOD = 10**9 + 7
EPS = 1e-6
KETA = 10**7


def main():
    H, W, K = MAP()
    x1, y1, x2, y2 = LIST()
    c = [["@"] + [c for c in input()] + ["@"] for i in range(H)]
    c = [["@"] * (W + 2)] + c + [["@"] * (W + 2)]
    c[x1][y1] = 0
    updated = []

    # 0123: 上下左右
    stack = [((x1 * KETA + y1) << 2) + 0, ((x1 * KETA + y1) << 2) + 1,
             ((x1 * KETA + y1) << 2) + 2, ((x1 * KETA + y1) << 2) + 3]
    DX = (1, 0, -1, 0)
    DY = (0, 1, 0, -1)
    head = 0
    while stack:
        head = 0
        new_stack = []
        while head < len(stack):
            b = stack[head]
            d = b % 4
            x, y = divmod(b >> 2, KETA)
            head += 1
            flag = True
            a = c[x][y] + 1
            for k in range(1, K + 1):
                xx, yy = x + k * DX[d], y + k * DY[d]
                if c[xx][yy] != ".":
                    flag = False
                    break
                if (xx, yy) == (x2, y2):
                    print(a)
                    return
                new_stack.append(((xx * KETA + yy) << 2) + (d - 1) % 4)
                new_stack.append(((xx * KETA + yy) << 2) + (d + 1) % 4)
                updated.append((a, xx, yy))
            if flag:
                new_stack.append(((xx * KETA + yy) << 2) + d)
        stack = new_stack
        for a, xx, yy in updated:
            c[xx][yy] = a
        update = []

    print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return [LIST() for _ in range(n)]


INF = float("inf")
MOD = 10**9 + 7
EPS = 1e-6


def main():
    H, W, K = MAP()
    x1, y1, x2, y2 = LIST()
    c = [["@"] + [c for c in input()] + ["@"] for i in range(H)]
    c = [["@"] * (W + 2)] + c + [["@"] * (W + 2)]
    updated = []

    # 0123: 上下左右
    stack = [(0, x1, y1, 0), (0, x1, y1, 1),
             (0, x1, y1, 2), (0, x1, y1, 3)]
    DX = (1, 0, -1, 0)
    DY = (0, 1, 0, -1)
    head = 0
    while stack:
        head = 0
        new_stack = []
        while head < len(stack):
            curr, x, y, d = stack[head]
            head += 1
            flag = True
            a = curr + 1
            for k in range(1, K + 1):
                xx, yy = x + k * DX[d], y + k * DY[d]
                if c[xx][yy] != ".":
                    flag = False
                    break
                if (xx, yy) == (x2, y2):
                    print(a)
                    return
                new_stack.append((a, xx, yy, (d - 1) % 4))
                new_stack.append((a, xx, yy, (d + 1) % 4))
                updated.append((xx, yy))
            if flag:
                new_stack.append((a, xx, yy, d))
        stack = new_stack
        for xx, yy in updated:
            c[xx][yy] = "@"
        update = []

    print(-1)
    return


if __name__ == '__main__':
    main()