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
from collections import defaultdict, deque

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    h, w, k = MI()
    x1, y1, x2, y2 = MI()
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1

    mylist = [0] * h

    #tableの読み込み
    for i in range(h):
        temp = input().rstrip()
        temp = [temp[j] for j in range(w)]
        mylist[i] = temp
    #初期化
    distance = [[float('inf') for i in range(w)] for j in range(h)]
    distance[x1][y1] = 0
    d = deque()
    start = [x1, y1]
    goal = [x2, y2]
    d.append(start)
    index = 0
    result = -1
    move = [[-1,0],[1,0],[0,1],[0,-1]]

    while d and index <= k:
        pos = d.pop()
        x = pos[0]
        y = pos[1]
        dist = distance[x][y]
        for i in move:
            #tempxの初期化
            tempx = x
            tempy = y
            for l in range(k):
                tempx += i[0]
                tempy += i[1]
                if not ((tempx >= 0 and tempx <= h-1) and (tempy >= 0 and tempy <= w - 1)):
                    break
                if dist + 1 < distance[tempx][tempy] and mylist[tempx][tempy] == ".":
                    distance[tempx][tempy] = dist + 1
                    d.append([tempx, tempy])
                else:
                    break
    if distance[x2][y2] == float('inf'):
        print(-1)
    else:
        print(distance[x2][y2])
        
main()

Submission status: Time Limit Exceeded

Solution code:
#関数リスト
import sys
input = sys.stdin.readline
from collections import defaultdict, deque

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

h, w, k = MI()
x1, y1, x2, y2 = MI()
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1

mylist = [0] * h

#tableの読み込み
for i in range(h):
    temp = input().rstrip()
    temp = [temp[j] for j in range(w)]
    mylist[i] = temp
#初期化
distance = [[float('inf') for i in range(w)] for j in range(h)]
distance[x1][y1] = 0
d = deque()
start = [x1, y1]
goal = [x2, y2]
d.append(start)
index = 0
result = -1
move = [[-1,0],[1,0],[0,1],[0,-1]]

while d and index <= k:
    pos = d.pop()
    x = pos[0]
    y = pos[1]
    dist = distance[x][y]
    for i in move:
        #tempxの初期化
        tempx = x
        tempy = y
        for l in range(k):
            tempx += i[0]
            tempy += i[1]
            if not ((tempx >= 0 and tempx <= h-1) and (tempy >= 0 and tempy <= w - 1)):
                break
            if dist + 1 < distance[tempx][tempy] and mylist[tempx][tempy] == ".":
                distance[tempx][tempy] = dist + 1
                d.append([tempx, tempy])
            else:
                break
if distance[x2][y2] == float('inf'):
    print(-1)
else:
    print(distance[x2][y2])

Submission status: Time Limit Exceeded

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

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    

    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(int, input().split())
    field = [[False]*(w+2) for _ in range(h+2)]
    inf = 10 ** 6 * k
    for i in range(h):
        #False で覆うことでx,yの制限をなくす。
        s = [True if _ == '.' else False for _ in input()]
        field[i+1] = [False]+s+[False]
    ans = dijkstra(xs,ys,xg,yg,h,w,k,field)
    if ans == inf:
        print(-1)
    else:
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
def input():return stdin.readline().strip()
def move(f,fx,fy):
    if f=='L':return fx,fy-1
    if f=='R':return fx,fy+1
    if f=='U':return fx-1,fy
    return fx+1,fy
def go(to):
    newx,newy=move(to,x,y)
    if 0<=newx<n and 0<=newy<m and arr[newx][newy]!='@' and (arr[newx][newy]=='.' or ans[newx][newy]>=mov):
        if d==to and cd<k:newqueue.append((newx,newy,cd+1,d,mov))
        else:newqueue.append((newx,newy,1,to,mov+1))
n,m,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
x1-=1;y1-=1;x2-=1;y2-=1
arr=[]
for _ in range(n):arr.append(list(input()))
ans=[[1000000009]*m for i in range(n)]
queue=[(x1,y1,0,'-',0)] # x, y, curdashes, dir, moves
while queue:
    newqueue=[]
    for x,y,cd,d,mov in queue:
        ans[x][y]=min(mov,ans[x][y])
        arr[x][y]='#'
        go('U')
        go('D')
        go('L')
        go('R')
    queue=newqueue
# for i in ans:print(*i)
if ans[x2][y2]==1000000009:print(-1)
else:print(ans[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
def input():return stdin.readline().strip()
def move(f,fx,fy):
    if f=='L':return fx,fy-1
    if f=='R':return fx,fy+1
    if f=='U':return fx-1,fy
    return fx+1,fy
def go(to):
    newx,newy=move(to,x,y)
    if 0<=newx<n and 0<=newy<m and arr[newx][newy]!='@' and (arr[newx][newy]=='.' or ans[newx][newy][2]>=mov):
        if d==to and cd<k:newqueue.append((newx,newy,cd+1,d,mov))
        else:newqueue.append((newx,newy,1,to,mov+1))
n,m,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
x1-=1;y1-=1;x2-=1;y2-=1
arr=[]
for _ in range(n):arr.append(list(input()))
ans=[[0]*m for i in range(n)]
queue=[(x1,y1,0,'-',0)] # x, y, curdashes, dir, moves
while queue:
    newqueue=[]
    for x,y,cd,d,mov in queue:
        if ans[x][y]:ans[x][y]=min((cd,d,mov),ans[x][y],key=lambda t:t[2])
        else:ans[x][y]=(cd,d,mov)
        arr[x][y]='#'
        go('U')
        go('D')
        go('L')
        go('R')
    queue=newqueue
# for i in ans:print(*i)
if ans[x2][y2]==0:print(-1)
else:print(ans[x2][y2][2])

Submission status: Time Limit Exceeded

Solution code:
def move(f,fx,fy):
    if f=='L':return fx,fy-1
    if f=='R':return fx,fy+1
    if f=='U':return fx-1,fy
    return fx+1,fy
def go(to):
    newx,newy=move(to,x,y)
    if 0<=newx<n and 0<=newy<m and arr[newx][newy]!='@' and (arr[newx][newy]=='.' or ans[newx][newy][2]>=mov):
        if d==to and cd<k:newqueue.append((newx,newy,cd+1,d,mov))
        else:newqueue.append((newx,newy,1,to,mov+1))
n,m,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
x1-=1;y1-=1;x2-=1;y2-=1
arr=[]
for _ in range(n):arr.append(list(input()))
ans=[[0]*m for i in range(n)]
queue=[(x1,y1,0,'-',0)] # x, y, curdashes, dir, moves
while queue:
    newqueue=[]
    for x,y,cd,d,mov in queue:
        if ans[x][y]:ans[x][y]=min((cd,d,mov),ans[x][y],key=lambda t:t[2])
        else:ans[x][y]=(cd,d,mov)
        arr[x][y]='#'
        go('U')
        go('D')
        go('L')
        go('R')
    queue=newqueue
# for i in ans:print(*i)
if ans[x2][y2]==0:print(-1)
else:print(ans[x2][y2][2])

Submission status: Time Limit Exceeded

Solution code:
H,W,K=map(int,input().split())
x1,y1,x2,y2=map(lambda x:int(x)-1,input().split())

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

inf=10**7
cost=[[inf]*W for _ in range(H)]
cost[x1][y1]=0
from heapq import heapify,heappop,heappush
hq=[(0,x1,y1)]

while hq:
    t,x,y=heappop(hq)
    #北へ
    for i in range(1,K+1):
        if x-i<0 or pond[x-i][y]=="@":
            break
        if cost[x-i][y]>t+1:
            cost[x-i][y]=t+1
            heappush(hq,(t+1,x-i,y))
    #東へ
    for i in range(1,K+1):
        if y+i>W-1 or pond[x][y+i]=="@":
            break
        if cost[x][y+i]>t+1:
            cost[x][y+i]=t+1
            heappush(hq,(t+1,x,y+i))
    #南へ
    for i in range(1,K+1):
        if x+i>H-1 or pond[x+i][y]=="@":
            break
        if cost[x+i][y]>t+1:
            cost[x+i][y]=t+1
            heappush(hq,(t+1,x+i,y))
    #西へ
    for i in range(1,K+1):
        if y-i<0 or pond[x][y-i]=="@":
            break
        if cost[x][y-i]>t+1:
            cost[x][y-i]=t+1
            heappush(hq,(t+1,x,y-i))

if cost[x2][y2]==inf:
    print(-1)
    exit()  
print(cost[x2][y2])

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
from heapq import heappop, heappush
import sys
input = sys.stdin.readline
H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(lambda x: int(x)-1, input().split())
S = [input()[:-1] for _ in [0]*H]

dirs = [(-1, 0), (0, -1), (0, 1), (1, 0)]

@lru_cache(None)
def f(x, y):
    return abs(x-x2)+abs(y-y2)

INF = 1<<30
D = [[INF]*W for _ in [0]*H]

q = []
heappush(q, (f(x1, x2), 0, x1, y1))
while q:
    h, d, x, y = heappop(q)
    if d >= D[x][y]:
        continue
    D[x][y] = d

    for sgn in (1, -1):   
        for dx in range(1, K+1):
            _x = x+dx*sgn
            if _x < 0 or _x >= H or S[_x][y] == '@':
                break
            if d+1 >= D[_x][y]:
                continue
            heappush(q, (d+f(_x, y), d+1, _x, y))

        for dy in range(1, K+1):
            _y = y+dy*sgn
            if _y < 0 or _y >= W or S[x][_y] == '@':
                break
            if d+1 >= D[x][_y]:
                continue
            heappush(q, (d+f(x, _y), d+1, x, _y))

ans = D[x2][y2]
print(-1 if ans == INF else ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
# 文字列をinput()した場合、末尾に改行が入るので注意
def main():
  h,w,k=map(int,input().split())
  x1,y1,x2,y2=map(lambda x:int(x)-1,input().split())
  cmap=[input() for _ in range(h)]
  from heapq import heappop,heappush,heapify
  dv={'w':0,'n':1,'e':2,'s':3}
  inf=float('inf')
  seen=[[[inf]*4 for _ in range(w)] for _ in range(h)]
  todo=[[0,x1,y1,'w']]
  seen[x1][y1][dv['w']]=0
  heapify(todo)
  #d=[[-1]*w for _ in range(h)]
  cnt=1
  while todo:
    c,x,y,v=heappop(todo)
    #print(c,x,y,v)
    if (x,y)==(x2,y2):
      print((c+k-1)//k)
      exit()
      #break
    if v=='w':
      if seen[x][y][dv['n']]>k*((c+k-1)//k):
        heappush(todo,[k*((c+k-1)//k),x,y,'n'])
        seen[x][y][dv['n']]=k*((c+k-1)//k)
      if y>0 and cmap[x][y-1]!='@' and seen[x][y-1][dv['w']]>c+1:
        heappush(todo,[c+1,x,y-1,'w'])
        seen[x][y-1][dv['w']]=c+1
    elif v=='e':
      if seen[x][y][dv['s']]>k*((c+k-1)//k):
        heappush(todo,[k*((c+k-1)//k),x,y,'s'])
        seen[x][y][dv['s']]=k*((c+k-1)//k)
      if y<w-1 and cmap[x][y+1]!='@' and seen[x][y+1][dv['e']]>c+1:
        heappush(todo,[c+1,x,y+1,'e'])
        seen[x][y+1][dv['e']]=c+1
    elif v=='n':
      if seen[x][y][dv['e']]>k*((c+k-1)//k):
        heappush(todo,[k*((c+k-1)//k),x,y,'e'])
        seen[x][y][dv['e']]=k*((c+k-1)//k)
      if x>0 and cmap[x-1][y]!='@' and seen[x-1][y][dv['n']]>c+1:
        heappush(todo,[c+1,x-1,y,'n'])
        seen[x-1][y][dv['n']]=c+1
    elif v=='s':
      if seen[x][y][dv['w']]>k*((c+k-1)//k):
        heappush(todo,[k*((c+k-1)//k),x,y,'w'])
        seen[x][y][dv['w']]=k*((c+k-1)//k)
      if x<h-1 and cmap[x+1][y]!='@' and seen[x+1][y][dv['s']]>c+1:
        heappush(todo,[c+1,x+1,y,'s'])
        seen[x+1][y][dv['s']]=c+1

  print(-1)
  #for si in seen:
  #  print([min(sij) for sij in si])

if __name__=='__main__':
  #import datetime
  #print(datetime.datetime.now())
  main()
  #print(datetime.datetime.now())

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(lambda x:int(x)-1,input().split())
cmap=[input() for _ in range(h)]
from math import ceil
from heapq import heappop,heappush,heapify
dv={'w':0,'n':1,'e':2,'s':3}
seen=[[[0]*4 for _ in range(w)] for _ in range(h)]
todo=[[0,x1,y1,'w'],[0,x1,y1,'n'],[0,x1,y1,'e'],[0,x1,y1,'s']]

heapify(todo)
d=[[0]*w for _ in range(h)]
while todo:
  c,x,y,v=heappop(todo)
  if seen[x][y]==1:continue
  seen[x][y][dv[v]]=1
  d[x][y]=c
  if (x,y)==(x2,y2):
    print(ceil(c))
    #for di in d:
    #  print(di)
    exit()
  #print(c,x,y,v)
  if v=='w':
    if seen[x][y][dv['n']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'n'])
    if seen[x][y][dv['s']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'s'])
    while y>0 and cmap[x][y-1]!='@':
      y-=1
      c+=1/k
      if seen[x][y][dv['w']]==0:heappush(todo,[c,x,y,'w'])
  elif v=='e':
    if seen[x][y][dv['n']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'n'])
    if seen[x][y][dv['s']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'s'])
    while y<w-1 and cmap[x][y+1]!='@':
      y+=1
      c+=1/k
      if seen[x][y][dv['e']]==0:heappush(todo,[c,x,y,'e'])
  elif v=='n':
    if seen[x][y][dv['w']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'w'])
    if seen[x][y][dv['e']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'e'])
    while x>0 and cmap[x-1][y]!='@':
      x-=1
      c+=1/k
      if seen[x][y][dv['n']]==0:heappush(todo,[c,x,y,'n'])
  elif v=='s':
    if seen[x][y][dv['w']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'w'])
    if seen[x][y][dv['e']]==0 and cmap[x][y]!='@':heappush(todo,[ceil(c),x,y,'e'])
    while x<h-1 and cmap[x+1][y]!='@':
      x+=1
      c+=1/k
      if seen[x][y][dv['s']]==0:heappush(todo,[c,x,y,'s'])

print(-1)
#print(d)

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(lambda x:int(x)-1,input().split())
c=[input() for _ in range(h)]
"""
ha=[]
for i in range(h):
  for j in range(w):
    if c[i][j]=='@':
      ha.append([i,j])
"""
from collections import deque
seen=[[0]*w for _ in range(h)]
todo=deque([[0,x1,y1]])
seen[x1][x2]=1
while todo:
  t,x,y=todo.popleft()

  if x==x2 and y==y2:
    print(t)
    exit(0)
  if x>0:
    for xi in range(x-1,max(x-k,0)-1,-1):
      if c[xi][y]=='@':break
      if seen[xi][y]==1:continue
      seen[xi][y]=1
      todo.append([t+1,xi,y])
  if x<h-1:
    for xi in range(x+1,min(x+k,h-1)+1):
      if c[xi][y]=='@':break
      if seen[xi][y]==1:continue
      seen[xi][y]=1
      todo.append([t+1,xi,y])
  if y>0:
    for yi in range(y-1,max(y-k,0)-1,-1):
      if c[x][yi]=='@':break
      if seen[x][yi]==1:continue
      seen[x][yi]=1
      todo.append([t+1,x,yi])
  if y<w-1:
    for yi in range(y+1,min(y+k,w-1)+1):
      if c[x][yi]=='@':break
      if seen[x][yi]==1:continue
      seen[x][yi]=1
      todo.append([t+1,x,yi])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque
INF = 10**18
 
h, w, k = map(int, input().split())
sx, sy, gx, gy = map(int, input().split())
 
field = []
dist = []
field.append("@" * (w + 2))
dist.append([-1] * (w + 2))
for _ in range(h):
    line = "".join(["@", input().rstrip(), "@"])
    field.append(line)
    dist.append([-1] + [INF] * (w) + [-1])
field.append("@" * (w + 2))
dist.append([-1] * (w + 2))
 
# for line in field:
#     print(line)
dist[sx][sy] = 0
delta = ((0, 1), (0, -1), (-1, 0), (1, 0))

def encode(x, y, d, k):
    return x * 10**18 + y * 10**10 + (d[0] + 1) * 10**9 + (d[1] + 1) * 10**8 + k

def decode(index):
    x = index // 10**18
    index %= 10**18
    y = index // 10**10
    index %= 10**10
    dx = index // 10**9
    index %= 10**9
    dx -= 1
    dy = index // 10**8
    index %= 10**8
    dy -= 1
    k = index
    return x, y, dx, dy, k
 
def bfs(x, y):
    dq = deque()
    dist[x][y] = 0
    for dx, dy in delta:
        if field[x+dx][y+dy] == ".":
            dq.append(encode(x+dx, y+dy, (dx, dy), k))
    while dq:
        x, y, dx, dy, step = decode(dq.popleft())
        ncost = dist[x - dx][y - dy] + 1 - (step < k)
        if ncost > dist[x][y]:
            continue
        else:
            dist[x][y] = ncost
        if step > 1:
            if field[x+dx][y+dy] == "." and dist[x+dx][y+dy] >= dist[x][y]:
                dq.appendleft(encode(x + dx, y + dy, (dx, dy), step - 1))
            for nd in delta:
                nx = x + nd[0]; ny = y + nd[1]
                if nd == (dx, dy) or nd == (-dx, -dy):
                    continue
                if field[nx][ny] == "." and dist[nx][ny] >= dist[x][y] + 1:
                    dq.append(encode(nx, ny, nd, k))
        else:
            for nd in delta:
                nx = x + nd[0]; ny = y + nd[1]
                if nd == (-dx, -dy):
                    continue
                if field[nx][ny] == "." and dist[nx][ny] >= dist[x][y] + 1:
                    dq.append(encode(nx, ny, nd, k))
 
bfs(sx, sy)
# for line in dist:
#     print(" ".join([str(item) for item in line]))
if dist[gx][gy] == INF:
    print(-1)
else:
    print(dist[gx][gy])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque
INF = 10**18
 
h, w, k = map(int, input().split())
sx, sy, gx, gy = map(int, input().split())
 
field = []
dist = []
field.append("@" * (w + 2))
dist.append([-1] * (w + 2))
for _ in range(h):
    line = "".join(["@", input().rstrip(), "@"])
    field.append(line)
    dist.append([-1] + [INF] * (w) + [-1])
field.append("@" * (w + 2))
dist.append([-1] * (w + 2))
 
# for line in field:
#     print(line)
dist[sx][sy] = 0
delta = ((0, 1), (0, -1), (-1, 0), (1, 0))

def encode(x, y, d, k):
    return x * 10**30 + y * 10**20 + (d[0] + 1) * 10**14 + (d[1] + 1) * 10**10 + k

def decode(index):
    x = index // 10**30
    index -= x * 10**30
    y = index // 10**20
    index -= y * 10**20
    dx = index // 10**14
    index -= dx * 10**14
    dx -= 1
    dy = index // 10**10
    index -= dy * 10**10
    dy -= 1
    k = index
    return x, y, dx, dy, k
 
def bfs(x, y):
    dq = deque()
    dist[x][y] = 0
    for dx, dy in delta:
        if field[x+dx][y+dy] == ".":
            dq.append(encode(x+dx, y+dy, (dx, dy), k))
    while dq:
        x, y, dx, dy, step = decode(dq.popleft())
        ncost = dist[x - dx][y - dy] + 1 - (step < k)
        if ncost > dist[x][y]:
            continue
        else:
            dist[x][y] = ncost
        if step > 1:
            if field[x+dx][y+dy] == "." and dist[x+dx][y+dy] >= dist[x][y]:
                dq.appendleft(encode(x + dx, y + dy, (dx, dy), step - 1))
            for nd in delta:
                nx = x + nd[0]; ny = y + nd[1]
                if nd == (dx, dy) or nd == (-dx, -dy):
                    continue
                if field[nx][ny] == "." and dist[nx][ny] >= dist[x][y] + 1:
                    dq.append(encode(nx, ny, nd, k))
        else:
            for nd in delta:
                nx = x + nd[0]; ny = y + nd[1]
                if nd == (-dx, -dy):
                    continue
                if field[nx][ny] == "." and dist[nx][ny] >= dist[x][y] + 1:
                    dq.append(encode(nx, ny, nd, k))
 
bfs(sx, sy)
# for line in dist:
#     print(" ".join([str(item) for item in line]))
if dist[gx][gy] == INF:
    print(-1)
else:
    print(dist[gx][gy])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split())
grid = [input() for _ in range(H)]

INF = float('inf')
path = [[[(INF, INF)] * 4 for _ in range(W)] for _ in range(H)]

D = [(-1, 0), (0, 1), (1, 0), (0, -1)] # 上:0, 右:1, 下:2, 左:3

# 初期処理
q = deque()
for d in range(4):
    path[x1][y1][d] = (1, 0)  # スタート地点では(1, 0)
    q.append((x1, y1, d, 1, 0)) # (x, y, 進行方向[d], 移動回数[c], 進行済マス数[k])

# 01BFS
while q:
    x, y, d, c, k = q.popleft()

    # nx, ny: 次の座標
    # nd: 次の進行方向
    # nc: 次の移動回数
    # nk: 次の進行済マス数
    for nd in range(4):
        if nd == d:
            dx, dy = D[nd]
            nk = 1 if k == K else k + 1
            nc = c + 1 if k == K else c
        else:
            dx, dy = 0, 0
            nk = 0
            nc = c + 1
        nx = x + dx; ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == '.' and path[nx][ny][nd] > (nc, nk):
            path[nx][ny][nd] = (nc, nk)
            if nc == c:
                q.appendleft((nx, ny, nd, nc, nk))
            else:
                q.append((nx, ny, nd, nc, nk))

# ゴール地点の最小コストを求める
ans = INF
for d in range(4):
    ans = min(ans, path[x2][y2][d][0])
ans = -1 if ans == INF else ans
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
h,w,k = map(int, sys.stdin.readline().rstrip("\n").split())
sx,sy,gx,gy = map(int, sys.stdin.readline().rstrip("\n").split())
sx,sy,gx,gy = sx-1,sy-1,gx-1,gy-1
labyrinth = [line.rstrip("\n") for line in sys.stdin]
INF = float('inf')
footprint = [ [[(INF,INF)]*4 for j in range(w)] for i in range(h) ]
m = [(-1, 0), (0, 1), (1, 0), (0, -1)]
q = deque()
for d in range(4):
    footprint[sx][sy][d] = (1,0)
    q.append((sx,sy,d,1,0))
while q:
    x, y, d, c, kk = q.popleft()
    for nd in range(4):
        if nd == d:
            mx,my = m[d]
            nkk = 1 if kk == k else kk + 1
            nc = c + 1 if kk == k else c
        else:
            mx,my = 0,0
            nkk = 0
            nc = c + 1
        nx = x + mx
        ny = y + my
        if 0 <= nx < h and 0 <= ny < w and labyrinth[nx][ny] == '.' and footprint[nx][ny][nd] > (nc, nkk):
            footprint[nx][ny][nd] = (nc, nkk)
            if nc == c:
                q.appendleft((nx, ny, nd, nc, nkk))
            else:
                q.append((nx, ny, nd, nc, nkk))
ans = INF
for d in range(4):
    ans = min(ans, footprint[gx][gy][d][0])
ans = -1 if ans == INF else ans
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)