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 heapq
def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w) for _ in range(h)]
    for i in range(h):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j] = 0
    x1, y1, x2, y2 = x1-1, y1-1, x2-1, y2-1
    hq = [[0, (x1, y1)]]
    st = set()
    R = set()
    L = set()
    U = set()
    D = set()
    dic = {}
    dic[(x1, y1)] = 0
    ans = -1
    while len(hq) > 0:
        cost, p = heapq.heappop(hq)
        if p in st:
            continue
        else:
            st.add(p)
        x, y = p[0], p[1]
        if x == x2 and y == y2:
            ans = cost
            break
        c = cost + 1
        for i in range(1, k+1):
            np = (x-i, y)
            if x-i < 0:
                break
            if np in D or np in st or pond[x-i][y] == 1:
                break
            if np in dic and dic[np] <= c:
                U.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x-i, y)])
            U.add(np)
        for i in range(1, k+1):
            np = (x+i, y)
            if h <= x+i:
                break
            if np in U or np in st or pond[x+i][y] == 1:
                break
            if np in dic and dic[np] <= c:
                D.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x+i, y)])
            D.add(np)
        for i in range(1, k+1):
            np = (x, y-i)
            if y-i < 0:
                break
            if np in R or np in st or pond[x][y-i] == 1:
                break
            if np in dic and dic[np] <= c:
                L.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x, y-i)])
            L.add(np)
        for i in range(1, k+1):
            np = (x, y+i)
            if w <= y+i:
                break
            if np in L or np in st or pond[x][y+i] == 1:
                break
            if np in dic and dic[np] <= c:
                R.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x, y+i)])
            R.add(np)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq
from numba import jit

@jit
def main(h, w, k, x1, y1, x2, y2, pond):
    hq = [[0, (x1, y1)]]
    st = set()
    R = set()
    L = set()
    U = set()
    D = set()
    dic = {}
    dic[(x1, y1)] = 0
    ans = -1
    while len(hq) > 0:
        cost, p = heapq.heappop(hq)
        if p in st:
            continue
        else:
            st.add(p)
        x, y = p[0], p[1]
        if x == x2 and y == y2:
            ans = cost
            break
        c = cost + 1
        for i in range(1, k+1):
            np = (x-i, y)
            if np in D or np in st or pond[x-i][y] == 1:
                break
            if np in dic and dic[np] <= c:
                U.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x-i, y)])
            U.add(np)
        for i in range(1, k+1):
            np = (x+i, y)
            if np in U or np in st or pond[x+i][y] == 1:
                break
            if np in dic and dic[np] <= c:
                D.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x+i, y)])
            D.add(np)
        for i in range(1, k+1):
            np = (x, y-i)
            if np in R or np in st or pond[x][y-i] == 1:
                break
            if np in dic and dic[np] <= c:
                L.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x, y-i)])
            L.add(np)
        for i in range(1, k+1):
            np = (x, y+i)
            if np in L or np in st or pond[x][y+i] == 1:
                break
            if np in dic and dic[np] <= c:
                R.add(np)
                continue
            dic[np] = c
            heapq.heappush(hq, [c, (x, y+i)])
            R.add(np)
    print(ans)

if __name__ == "__main__":
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j+1] = 0
    main(h, w, k, x1, y1, x2, y2, pond)

Submission status: Time Limit Exceeded

Solution code:
import heapq
from numba import jit

def calc_cost(row, pt):
    return row*10**8 + pt

@jit
def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j+1] = 0
    hq = []
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 0])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 1])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 2])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 3])
    ans = [[[float("inf")]*4 for j in range(w+2)] for i in range(h+2)]
    ans[x1][y1][0] = calc_cost(1, 0)
    ans[x1][y1][1] = calc_cost(1, 0)
    ans[x1][y1][2] = calc_cost(1, 0)
    ans[x1][y1][3] = calc_cost(1, 0)
    while len(hq) > 0:
        cost, row, pt, x, y, vec = heapq.heappop(hq)
        if cost > ans[x][y][vec]:
            continue
        for i in range(4):
            if vec == i:
                nx, ny = x, y
                if i == 0:
                    nx -= 1
                elif i == 1:
                    ny += 1
                elif i == 2:
                    nx += 1
                else:
                    ny -= 1
                if pond[nx][ny] == 1:
                    continue
                nrow, npt = row, pt
                if pt == k:
                    nrow += 1
                    npt = 1
                else:
                    npt += 1
                ncost = calc_cost(nrow, npt)
                if ncost < ans[nx][ny][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, nx, ny, i])
                    ans[nx][ny][i] = ncost
            else:
                nrow, npt = row+1, 0
                ncost = calc_cost(nrow, npt)
                if ncost < ans[x][y][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, x, y, i])
                    ans[x][y][i] = ncost
    tmp = float("inf")
    for i in range(4):
        if ans[x2][y2][i] // 10**8 < tmp:
            tmp = ans[x2][y2][i] // 10**8
    if tmp == float("inf"):
        print(-1)
    else:
        print(tmp)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq

def calc_cost(row, pt):
    return row*10**8 + pt

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j+1] = 0
    hq = []
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 0])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 1])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 2])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 3])
    ans = [[[float("inf")]*4 for j in range(w+2)] for i in range(h+2)]
    ans[x1][y1][0] = calc_cost(1, 0)
    ans[x1][y1][1] = calc_cost(1, 0)
    ans[x1][y1][2] = calc_cost(1, 0)
    ans[x1][y1][3] = calc_cost(1, 0)
    brk = 0
    while len(hq) > 0:
        cost, row, pt, x, y, vec = heapq.heappop(hq)
        if cost > ans[x][y][vec]:
            continue
        if x == x2 and y == y2:
            brk += 1
        if brk == 4:
            break
        for i in range(4):
            if vec == i:
                nx, ny = x, y
                if i == 0:
                    nx -= 1
                elif i == 1:
                    ny += 1
                elif i == 2:
                    nx += 1
                else:
                    ny -= 1
                if pond[nx][ny] == 1:
                    continue
                nrow, npt = row, pt
                if pt == k:
                    nrow += 1
                    npt = 1
                else:
                    npt += 1
                ncost = calc_cost(nrow, npt)
                if ncost < ans[nx][ny][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, nx, ny, i])
                    ans[nx][ny][i] = ncost
            else:
                nrow, npt = row+1, 0
                ncost = calc_cost(nrow, npt)
                if ncost < ans[x][y][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, x, y, i])
                    ans[x][y][i] = ncost
    tmp = float("inf")
    for i in range(4):
        if ans[x2][y2][i] // 10**8 < tmp:
            tmp = ans[x2][y2][i] // 10**8
    if tmp == float("inf"):
        print(-1)
    else:
        print(tmp)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq

def calc_cost(row, pt):
    return row*10**8 + pt

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j+1] = 0
    hq = []
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 0])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 1])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 2])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 3])
    ans = [[[float("inf")]*4 for j in range(w+2)] for i in range(h+2)]
    ans[x1][y1][0] = calc_cost(1, 0)
    ans[x1][y1][1] = calc_cost(1, 0)
    ans[x1][y1][2] = calc_cost(1, 0)
    ans[x1][y1][3] = calc_cost(1, 0)
    while len(hq) > 0:
        cost, row, pt, x, y, vec = heapq.heappop(hq)
        if cost > ans[x][y][vec]:
            continue
        for i in range(4):
            if vec == i:
                nx, ny = x, y
                if i == 0:
                    nx -= 1
                elif i == 1:
                    ny += 1
                elif i == 2:
                    nx += 1
                else:
                    ny -= 1
                if pond[nx][ny] == 1:
                    continue
                nrow, npt = row, pt
                if pt == k:
                    nrow += 1
                    npt = 1
                else:
                    npt += 1
                ncost = calc_cost(nrow, npt)
                if ncost < ans[nx][ny][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, nx, ny, i])
                    ans[nx][ny][i] = ncost
            else:
                nrow, npt = row+1, 0
                ncost = calc_cost(nrow, npt)
                if ncost < ans[x][y][i]:
                    heapq.heappush(hq, [ncost, nrow, npt, x, y, i])
                    ans[x][y][i] = ncost
    tmp = float("inf")
    for i in range(4):
        if ans[x2][y2][i] // 10**8 < tmp:
            tmp = ans[x2][y2][i] // 10**8
    if tmp == float("inf"):
        print(-1)
    else:
        print(tmp)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq

def calc_cost(row, pt):
    return row*10**8 + pt

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[1]*(w+2) for _ in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                pond[i][j+1] = 0
    hq = []
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 0])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 1])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 2])
    heapq.heappush(hq, [calc_cost(1, 0), 1, 0, x1, y1, 3])
    ans = [[[float("inf")]*4 for j in range(w+2)] for i in range(h+2)]
    ans[x1][y1][0] = calc_cost(1, 0)
    ans[x1][y1][1] = calc_cost(1, 0)
    ans[x1][y1][2] = calc_cost(1, 0)
    ans[x1][y1][3] = calc_cost(1, 0)
    while len(hq) > 0:
        cost, row, pt, x, y, vec = heapq.heappop(hq)
        for i in range(4):
            if cost > ans[x][y][i]:
                continue
            nx, ny = x, y
            nrow, npt, = row, pt
            ncost = cost
            if i == 0:
                nx -= 1
            elif i == 1:
                ny += 1
            elif i == 2:
                nx += 1
            else:
                ny -= 1
            if pond[nx][ny] == 1:
                continue
            if i == vec:
                if pt == k:
                    nrow += 1
                    npt = 1
                else:
                    npt += 1
            else:
                npt = 1
                nrow += 1
            ncost = calc_cost(nrow, npt)
            if ncost < ans[nx][ny][i]:
                ans[nx][ny][i] = ncost
                heapq.heappush(hq, [ncost, nrow, npt, nx, ny, i])
    tmp = float("inf")
    for i in range(4):
        if ans[x2][y2][i] // 10**8 < tmp:
            tmp = ans[x2][y2][i] // 10**8
    if tmp == float("inf"):
        print(-1)
    else:
        print(tmp)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

INF = 10**18

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

queue = deque()
queue.append((x1, y1))

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

dist = [[INF for j in range(W)] for i in range(H)]
dist[x1][y1] = 0

while queue:
    x, y = queue.popleft()
    for i in range(4):
        for k in range(K):
            nx = x + (k + 1) * dx[i]
            ny = y + (k + 1) * dy[i]
            if not (0 <= nx < H and 0 <= ny < W):
                break
            if C[nx][ny] == '@':
                break
            if dist[nx][ny] < dist[x][y] + 1:
                break
            if dist[nx][ny] != INF:
                continue
            dist[nx][ny] = dist[x][y] + 1
            queue.append((nx, ny))

print(dist[x2][y2] if dist[x2][y2] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

INF = 10**18

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

queue = deque()
queue.append((x1, y1))

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

dist = [[INF for j in range(W)] for i in range(H)]
dist[x1][y1] = 0

while queue:
    x, y = queue.popleft()
    for i in range(4):
        for k in range(K):
            nx = x + (k + 1) * dx[i]
            ny = y + (k + 1) * dy[i]
            if not (0 <= nx < H and 0 <= ny < W):
                break
            if C[nx][ny] == '@':
                break
            if dist[nx][ny] <= dist[x][y]:
                break
            if dist[nx][ny] != INF:
                continue
            dist[nx][ny] = dist[x][y] + 1
            queue.append((nx, ny))

print(dist[x2][y2] if dist[x2][y2] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

H,W,K=map(int,input().split())
sy,sx,gy,gx=map(int,input().split())
st=sx+sy*(W+2)
gl=gx+gy*(W+2)
c=['@']*(W+2)
for i in range(H):
    c.extend(['@']+list(input())+['@'])
c.extend(['@']*(W+2))
que=deque()
dist=[INF]*(W+2)*(H+2)
que.append(st)
dist[st]=0
d=(-1,1,W+2,-(W+2))
while que:
    v=que.popleft()
    tmp_dist=dist[v]
    for k in range(4):
        nv=v
        for _ in range(K):
            nv+=+d[k]
            if c[nv]=='.' and dist[nv]>tmp_dist:
                    dist[nv]=tmp_dist+1
                    que.append(nv)
            else:
                break
print(dist[gl] if dist[gl]!=INF else -1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

H,W,K=map(int,input().split())
sy,sx,gy,gx=map(int,input().split())
st=sx+sy*(W+2)
gl=gx+gy*(W+2)
c=['@']*(W+2)
for i in range(H):
    c.extend(['@']+list(input())+['@'])
c.extend(['@']*(W+2))
que=deque()
dist=[INF]*(W+2)*(H+2)
que.append(st)
dist[st]=0
d=(-1,1,W+2,-(W+2))
while que:
    v=que.popleft()
    tmp_dist=dist[v]+1
    for k in range(4):
        nv=v
        for _ in range(K):
            nv+=+d[k]
            if c[nv]=='.':
                if dist[nv]>tmp_dist:
                    dist[nv]=tmp_dist
                    que.append(nv)
            else:
                break
print(dist[gl] if dist[gl]!=INF else -1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

H,W,K=map(int,input().split())
sy,sx,gy,gx=map(int,input().split())
st=sx+sy*(W+2)
gl=gx+gy*(W+2)
c=['@']*(W+2)
for i in range(H):
    c.extend(['@']+list(input())+['@'])
c.extend(['@']*(W+2))
que=deque()
d=[INF]*(W+2)*(H+2)
direction=[[0]*4 for _ in range((H+2)*(W+2))]
que.append(st)
d[st]=0
di=(-1,1,W+2,-(W+2))
while que:
    v=que.popleft()
    for k in range(4):
        nv=v+di[k]
        if c[nv]=='.':
            if direction[v][k]>0:
                if d[nv]>d[v]:
                    direction[nv]=[0]*4
                    direction[nv][k]=direction[v][k]-1
                    direction[v][k]=0
                    d[nv]=d[v]
                    que.append(nv)
                elif d[nv]==d[v]:
                    direction[v][k]=0
                    direction[nv][k]=direction[v][k]-1
            else:
                if d[nv]>d[v]+1:
                    direction[nv]=[0]*4
                    direction[nv][k]=K-1
                    direction[v][k]=0
                    d[nv]=d[v]+1
                    que.append(nv)
                elif d[nv]==d[v]+1:
                    direction[v][k]=0
                    direction[nv][k]=K-1
print(d[gl] if d[gl]!=INF else -1)

Submission status: Time Limit Exceeded

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

def arr_4(x):
  return [x,x,x,x]

H, W, K = map(int, input().split())
INF = 10 * H * W

x1, y1, x2, y2 = map(int, input().split())
start = (x1-1 ,y1-1, 0)
goal = (x2-1, y2-1, 0)

G = [list(map(arr_4,input().rstrip())) for _ in range(H)]
#G[i][j][k]: (i,j)座標、k方向(0-3)

def dijkstra(G, start, goal):# G:格子、G[i][j][l] = 0 なら通過可、1ならコスト+1 
  H = len(G)
  W = len(G[0])
  #Dir = 4 方向
  task = [] 
  min_cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  #prev_points = [[[(-2,-2) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  for i in range(4):
    heappush(task, ((1, 0), (start[0], start[1], i), start)) 
    
  #（開始）頂点、コスト、前の点
  # !!コストは（加速回数、慣性で進んだ距離）で規定!! #
  # !!最初の点番号が0でないときは、真ん中の0を変更する!! #
  
  flag = 0
  while task:
    while task:
      c, p, prev = heappop(task)    
      if not G[p[0]][p[1]][p[2]] == "@":
        break  
      if len(task) == 0:
        flag = 1
    if flag == 1:
      break
    #print(task)
    G[p[0]][p[1]][p[2]] = "@"
    min_cost[p[0]][p[1]][p[2]] = c
    #prev_points[p[0]][p[1]] = prev
    
    if p[0] == goal[0] and p[1] == goal[1]:
      return min_cost#, prev_points)
  
    #次の頂点を列挙
    q = []
    if p[0] > 0 and p[2] == 0:#南
      q.append((p[0]-1,p[1],p[2])) 
    if p[0] < H-1 and p[2] == 1:#北
      q.append((p[0]+1,p[1],p[2])) 
    if p[1] > 0 and p[2] == 2:#西
      q.append((p[0],p[1]-1,p[2])) 
    if p[1] < W-1 and p[2] == 3:#東
      q.append((p[0],p[1]+1,p[2]))   
    for i in range(4):
      if not i == p[2]:
        q.append((p[0],p[1],i)) 
    
    for j in q: #制約が入るときはここに追加
      if G[j[0]][j[1]][j[2]] == "@": continue
      
      if p[2] == j[2]:#向き変更なし
        if c[1] == K:
          cost_next = (c[0]+1,1)
        else:
          cost_next = (c[0],c[1]+1)
      else:#向き変更
        cost_next = (c[0]+1,0)
      
      if cost[j[0]][j[1]][j[2]] > cost_next:
        cost[j[0]][j[1]][j[2]] = cost_next
        heappush(task, (cost_next, j, p))
        #print(cost_next, j, p)  
      #print(task)
      
    del q
    
  return min_cost#, prev_points)

min_cost = dijkstra(G, start, goal)

#print(min_cost)

c = min(min_cost[x2-1][y2-1])[0]
if x1 == x2 and y1 == y2:
  c = 0
print(c if c < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify,heappush,heappop

def arr_4(x):
  return [x,x,x,x]

H, W, K = map(int, input().split())
INF = 10 * H * W

x1, y1, x2, y2 = map(int, input().split())
start = (x1-1 ,y1-1, 0)
goal = (x2-1, y2-1, 0)

G = [list(map(arr_4,input())) for _ in range(H)]
#G[i][j][k]: (i,j)座標、k方向(0-3)

def dijkstra(G, start, goal):# G:格子、G[i][j][l] = 0 なら通過可、1ならコスト+1 
  H = len(G)
  W = len(G[0])
  #Dir = 4 方向
  task = [] 
  min_cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  cost = [[[(INF,0) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  #prev_points = [[[(-2,-2) for _ in range(4)] for _ in range(W)] for _ in range(H)]
  for i in range(4):
    heappush(task, ((1, 0), (start[0], start[1], i), start)) 
    
  #（開始）頂点、コスト、前の点
  # !!コストは（加速回数、慣性で進んだ距離）で規定!! #
  # !!最初の点番号が0でないときは、真ん中の0を変更する!! #
  
  flag = 0
  while task:
    while task:
      c, p, prev = heappop(task)    
      if not G[p[0]][p[1]][p[2]] == "@":
        break  
      if len(task) == 0:
        flag = 1
    if flag == 1:
      break
    #print(task)
    G[p[0]][p[1]][p[2]] = "@"
    min_cost[p[0]][p[1]][p[2]] = c
    #prev_points[p[0]][p[1]] = prev
    
    if p[0] == goal[0] and p[1] == goal[1]:
      return min_cost#, prev_points)
  
    #次の頂点を列挙
    q = []
    if p[0] > 0 and p[2] == 0:#南
      q.append((p[0]-1,p[1],p[2])) 
    if p[0] < H-1 and p[2] == 1:#北
      q.append((p[0]+1,p[1],p[2])) 
    if p[1] > 0 and p[2] == 2:#西
      q.append((p[0],p[1]-1,p[2])) 
    if p[1] < W-1 and p[2] == 3:#東
      q.append((p[0],p[1]+1,p[2]))   
    for i in range(4):
      if not i == p[2]:
        q.append((p[0],p[1],i)) 
    
    for j in q: #制約が入るときはここに追加
      if G[j[0]][j[1]][j[2]] == "@": continue
      
      if p[2] == j[2]:#向き変更なし
        if c[1] == K:
          cost_next = (c[0]+1,1)
        else:
          cost_next = (c[0],c[1]+1)
      else:#向き変更
        cost_next = (c[0]+1,0)
      
      if cost[j[0]][j[1]][j[2]] > cost_next:
        cost[j[0]][j[1]][j[2]] = cost_next
        heappush(task, (cost_next, j, p))
        #print(cost_next, j, p)  
      #print(task)
      
    del q
    
  return min_cost#, prev_points)

min_cost = dijkstra(G, start, goal)

#print(min_cost)

c = min(min_cost[x2-1][y2-1])[0]
if x1 == x2 and y1 == y2:
  c = 0
print(c if c < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
    input = sys.stdin.readline
    Dy = [0,1,0,-1]
    Dx = [1,0,-1,0]
    H, W, K = map(int, input().split())
    y1,x1,y2,x2 = map(int, input().split())
    C = ["@" + input() for _ in range(H)]
    C = ["@"*(W+2)] + C + ["@"*(W+2)]
    Nexts = [[[1]*(W+2) for _ in range(H+2)] for _ in range(4)]
    q = [(y1, x1)]
    ans = 0
    while q:
        q_new = []
        for y0, x0 in q:
            if (y0, x0) == (y2, x2):
                print(ans)
                exit()
            for dy, dx, Next in zip(Dy, Dx, Nexts):
                y, x = y0, x0
                sum_next = 0
                Path = [(y, x)]
                while True:
                    sum_next += Next[y][x]
                    y = y0 + dy * sum_next
                    x = x0 + dx * sum_next
                    if sum_next > K or C[y][x] != ".":
                        break
                    Path.append((y, x))
                    q_new.append((y, x))
                for path_y, path_x in Path:
                    Next[path_y][path_x] = abs(path_y-y) + abs(path_x-x)
        q = q_new
        ans += 1
    print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush 
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()

    # 多分正解だけどpythonではTLEする。
    def dijkstra():
        def toId(x, y, v): return (x*w+y)*4 + v

        def modCeil(x): return x + (-x)%k

        def push(x, y, v, cost):
            nId = toId(x, y, v)
            if dist[nId] > cost:
                dist[nId] = cost
                heappush(que, (cost, nId))

        inf = 1e18

        dist = [inf]*(h*w*4)
        dist[toId(xs, ys, 0)] = 0

        que = [(0, toId(xs, ys, 0))]
        dx = [-1, 0, 1, 0]
        dy = [0, 1, 0, -1]
        while que:
            cost, Id = heappop(que)
            x = Id//4//w
            y = Id//4%w
            v = Id%4

            if cost > dist[Id]:
                continue
            
            for nv in range(4):
                nx = x + dx[nv]
                ny = y + dy[nv]
                if nx < 0 or nx >= h or ny < 0 or ny >= w: continue
                if field[nx][ny] == '@': continue
                if v == nv:
                    push(nx, ny, nv, cost+1)
                else:
                    push(nx, ny, nv, modCeil(cost)+ 1)
            
        ans = min([dist[toId(xg, yg, v)] for v in range(4)])
        if ans == inf:
            print(-1)
        else:
            print(modCeil(ans)//k)
        

    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(lambda x: int(x)-1, input().split())
    field = [input() for _ in range(h)]
    dijkstra()


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush 
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()

    # 多分正解だけどpythonではTLEする。
    def dijkstra():
        def toId(x, y, v): return (x*w+y)*4 + v

        def modCeil(x): return x + (-x)%k

        def push(x, y, v, cost):
            nId = toId(x, y, v)
            if dp[nId] > cost:
                dp[nId] = cost
                heappush(que, (cost, nId))

        inf = 1e18

        dp = [inf]*(h*w*4)
        dp[toId(xs, ys, 0)] = 0

        que = [(0, toId(xs, ys, 0))]
        dx = [-1, 0, 1, 0]
        dy = [0, 1, 0, -1]
        while que:
            cost, Id = heappop(que)
            x = Id//4//w
            y = Id//4%w
            v = Id%4

            if cost > dp[Id]:
                continue
            
            for nv in range(4):
                push(x, y, nv, modCeil(cost))
            
            nx, ny = x+dx[v], y+dy[v]
            if 0 <= nx < h and 0 <= ny < w and field[nx][ny] == '.':
                push(nx, ny, v, cost+1)

        ans = inf
        for v in range(4):
            ans = min(ans, dp[toId(xg, yg, v)])
        if ans == inf:     
            return print(-1)
        return print(modCeil(ans)//k)

    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(lambda x: int(x)-1, input().split())
    field = [input() for _ in range(h)]
    dijkstra()


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    from collections import deque
    def input(): return sys.stdin.readline().rstrip()
    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(lambda x: int(x)-1, input().split())
    field = [input() for _ in range(h)]

    inf = 1e7

    dist = [[inf]*w for _ in range(h)]
    dist[xs][ys] = 0
    que = deque([(xs, ys)])
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    while que:
        x, y = que.popleft()
        for i in range(4):
            nx, ny = x, y
            for _ in range(k):
                nx += dx[i]
                ny += dy[i]
                if 0 <= nx < h and 0 <= ny < w:
                    if field[nx][ny] == '@': break
                    if dist[nx][ny] <= dist[x][y]: break
                    if dist[nx][ny] > dist[x][y] + 1:
                        dist[nx][ny] = dist[x][y] + 1
                        que.append((nx, ny))
        
    if dist[xg][yg] == inf:
        print(-1)
    else:
        print(dist[xg][yg])
    
if __name__ == '__main__':
    main()