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
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf if c[i][j]=="." else -1 for j in range(w)] for i in range(h)]
now=deque()
now.append([x1-1,y1-1])
dp[x1-1][y1-1]=0
#kの更新が遅い
def bfs(d):
    global h,w,k,dp,now,x2,y2
    l=len(now)
    if l==0:
        return
    dp_sub=deque()
    cand=set()
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if dp[x][y+j]==inf:
                dp_sub.append([x,y+j,d])
                #dp[x][y+j]=d
                cand.add((x,y+j))
                #now.append([x,y+j])
            else:
                break
        for j in range(1,min(k+1,y+1)):
            if dp[x][y-j]==inf:
                dp_sub.append([x,y-j,d])
                #dp[x][y-j]=d
                cand.add((x,y-j))
                #now.append([x,y-j])
            else:
                break
        for j in range(1,min(k+1,h-x)):
            if dp[x+j][y]==inf:
                dp_sub.append([x+j,y,d])
                #dp[x+j][y]=d
                cand.add((x+j,y))
                #now.append([x+j,y])
            else:
                break
        for j in range(1,min(k+1,x+1)):
            if dp[x-j][y]==inf:
                dp_sub.append([x-j,y,d])
                #dp[x-j][y]=d
                cand.add((x-j,y))
                #now.append([x-j,y])
            else:
                break
    while dp_sub!=deque([]):
        e=dp_sub.popleft()
        dp[e[0]][e[1]]=e[2]
    for i in cand:
        now.append(i)
    bfs(d+1)
bfs(1)
print(dp[x2-1][y2-1] if dp[x2-1][y2-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
def f_pond_skater():
    from fractions import Fraction
    from heapq import heappop, heappush
    from math import ceil
    H, W, K = [int(i) for i in input().split()]
    start_row, start_col, target_row, target_col = [int(i) - 1 for i in input().split()]
    Grid = [input() for _ in range(H)]

    def is_inside(row, col):
        return (0 <= row < H) and (0 <= col < W)

    dp = [[[float('inf')] * 4 for j in range(W)] for i in range(H)]
    dr, dc = (0, -1, 0, 1), (-1, 0, 1, 0)  # '0123' と '左上右下' を対応
    queue = [(0, start_row, start_col, i) for i in range(4)]
    while queue:
        cost, row, col, direction = heappop(queue)
        dp[row][col][direction] = cost

        # 1マス直進する
        nr, nc = row + dr[direction], col + dc[direction]
        if (is_inside(nr, nc) and Grid[nr][nc] == '.' and
                dp[nr][nc][direction] > cost + Fraction(1, K)):
            heappush(queue, (dp[row][col][direction] + Fraction(1, K), nr, nc, direction))

        # 向きを 90 度変える
        for i in (1, 3):
            if dp[row][col][(direction + i) % 4] > ceil(float(cost)):
                heappush(queue, (ceil(float(cost)), row, col, (direction + i) % 4))

    ans = min(dp[target_row][target_col][d] for d in range(4))
    return ceil(float(ans)) if ans != float('inf') else -1

print(f_pond_skater())

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
INF = float('inf')


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    sy -= 1
    sx -= 1
    gx -= 1
    gy -=1
    lake = [list(readline().decode('utf-8').strip()) for _ in range(H)]
    dist = [[INF] * W for _ in range(H)]
    dxy = ((1, 0), (0, 1), (-1, 0), (0, -1))
    Q = deque()
    Q.append((sy, sx, 0))
    dist[sy][sx] = 0
    while Q:
        y,x,d = Q.popleft()
        if (y,x) == (gy, gx):
            print(d)
            sys.exit()
        for dx,dy in dxy:
            n_y = y
            n_x = x
            for _ in range(K):
                n_y +=dy
                n_x +=dx

                if 0<=n_x<W and 0<=n_y<H and lake[n_y][n_x] != '@':
                    if dist[n_y][n_x]<d:
                        break
                    elif dist[n_y][n_x] == INF:
                        dist[n_y][n_x] = d + 1
                        Q.append((n_y,n_x,d+1))
                    else:
                        continue

                else:
                    break
    print('-1')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
INF = float('inf')


H, W, K = map(int, readline().split())
sy, sx, gy, gx = map(int, readline().split())
sy -= 1
sx -= 1
gx -= 1
gy -=1
lake = [list(readline().decode('utf-8').strip()) for _ in range(H)]
dist = [[INF] * (W+2) for _ in range(H+2)]
dxy = ((1, 0), (0, 1), (-1, 0), (0, -1))
Q = deque()
Q.append((sy, sx, 0))
dist[sy][sx] = 0
while Q:
    y,x,d = Q.popleft()
    if (y,x) == (gy, gx):
        print(d)
        sys.exit()
    for dx,dy in dxy:
        n_y = y
        n_x = x
        for _ in range(K):
            n_y +=dy
            n_x +=dx

            if 0<=n_x<W and 0<=n_y<H and lake[n_y][n_x] != '@':
                if dist[n_y][n_x]<d:
                    break
                elif dist[n_y][n_x] == INF:
                    dist[n_y][n_x] = d + 1
                    Q.append((n_y,n_x,d+1))
                else:
                    continue

            else:
                break
print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
INF = float('inf')


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    sy -= 1
    sx -= 1
    gx -= 1
    gy -=1
    lake = [list(readline().decode('utf-8').strip()) for _ in range(H)]
    dist = [[INF] * (W+2) for _ in range(H+2)]
    dxy = ((1, 0), (0, 1), (-1, 0), (0, -1))
    Q = deque()
    Q.append((sy, sx, 0))
    dist[sy][sx] = 0
    while Q:
        y,x,d = Q.popleft()
        if (y,x) == (gy, gx):
            print(d)
            sys.exit()
        for dx,dy in dxy:
            n_y = y
            n_x = x
            for _ in range(K):
                n_y +=dy
                n_x +=dx

                if 0<=n_x<W and 0<=n_y<H and lake[n_y][n_x] != '@':
                    if dist[n_y][n_x]<d:
                        break
                    elif dist[n_y][n_x] == INF:
                        dist[n_y][n_x] = d + 1
                        Q.append((n_y,n_x,d+1))
                    else:
                        continue

                else:
                    break
    print('-1')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
INF = float('inf')


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    sy -= 1
    sx -= 1
    gx -= 1
    gy -=1
    lake = [list(readline().decode('utf-8').strip()) for _ in range(H)]
    dist = [[INF] * (W+2) for _ in range(H+2)]
    dxy = ((1, 0), (0, 1), (-1, 0), (0, -1))
    Q = deque()
    Q.append((sy, sx, 0))
    dist[sy][sx] = 0
    while Q:
        y,x,d = Q.popleft()
        if y == gy and x == gx:
            print(d)
            sys.exit()
        for dx,dy in dxy:
            n_y = y
            n_x = x
            for _ in range(K):
                n_y +=dy
                n_x +=dx

                if 0<=n_x<W and 0<=n_y<H and lake[n_y][n_x] != '@':
                    if 0<=dist[n_y][n_x]<d:
                        break
                    elif dist[n_y][n_x] == INF:
                        dist[n_y][n_x] = d + 1
                        Q.append((n_y,n_x,d+1))
                    else:
                        continue

                else:
                    break
    print('-1')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve():
    H, W, K = map(int, input().split())
    y1, x1, y2, x2 = map(int, input().split())
    l = [[1 if s=="@" else 0 for s in input()] for _ in range(H)]
    INF = 10**12

    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1

    ddy = [0, 0, -1, 1]
    ddx = [-1, 1, 0, 0]

    dist = defaultdict(lambda :INF)
    dist[(y1, x1)] = 0
    q = deque([(y1, x1)])

    while q:
        y, x = q.popleft()
        for i, (dy, dx) in enumerate(zip(ddy, ddx)):
            for j in range(1, K+1):
                if not (0<=y+dy*j<H and 0<=x+dx*j<W):
                    break
                if l[y+dy*j][x+dx*j]:
                    break

                if dist[(y+dy*j, x+dx*j)] > dist[(y, x)] + 1:
                    dist[(y+dy*j, x+dx*j)] = dist[(y, x)] + 1
                    q.append((y+dy*j, x+dx*j))


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


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline
from collections import deque
INF = float('inf')


def main():
    H, W, K = map(int, readline().split())
    # いつものパターンと問題文のi,jが逆なので、
    # 問題文のxを変数yに、問題文のyを変数xに代入している
    sy, sx, gy, gx = map(int, readline().split())
    lake = [['@' for _ in range(W+2)]]

    for _ in range(H):
        c = ['@'] + list(readline().decode('utf-8').strip()) + ['@']
        lake.append(c)
    lake.append(['@' for _ in range(W+2)])

    dist = [[INF] * (W+2) for _ in range(H+2)]
    dxy = ((1, 0), (0, 1), (-1, 0), (0, -1))
    Q = deque()
    Q.append((sy, sx, 0))
    dist[sy][sx] = 0
    while Q:
        y,x,d = Q.popleft()
        if y == gy and x == gx:
            print(d)
            sys.exit()
        for dx,dy in dxy:
            n_y = y
            n_x = x
            for k in range(K):
                n_y +=dy
                n_x +=dx

                if lake[n_y][n_x] == '.':
                    if dist[n_y][n_x] == INF:
                        dist[n_y][n_x] = d + 1
                        Q.append((n_y,n_x,d+1))
                    else:
                        continue

                else:
                    break
    print('-1')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

H, W, K = map(int, sys.stdin.readline().strip().split())
xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())

m = []
for _ in range(H):
    m.append(list(map(str, sys.stdin.readline().strip())))

M = [[float('inf')] * W for _ in range(H)]


def bfs(x1, y1, d):
    q = deque()
    q.append((d, x1, y1))

    while q:
        d, x1, y1 = q.popleft()

        M[x1][y1] = d

        if (x1 == xg - 1) and (y1 == yg - 1):
            break

        for dx, dy in ([0, 1], [1, 0], [0, -1], [-1, 0]):
            k = 1
            while k <= K:
                x2 = x1 + dx * k
                y2 = y1 + dy * k
                if x2 < 0 or x2 >= H:
                    break
                if y2 < 0 or y2 >= W:
                    break
                if m[x2][y2] == '@':
                    break
                if M[x2][y2] < d + 1:
                    break
                if M[x2][y2] == d + 1:
                    continue

                q.append((d + 1, x2, y2))

                k += 1


if m[xs - 1][ys - 1] != '@':
    bfs(xs - 1, ys - 1, 0)

# for i in range(len(M)):
#     print(M[i])


ans = M[xg - 1][yg - 1]
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

H, W, K = map(int, sys.stdin.readline().strip().split())
xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())

m = []
for _ in range(H):
    m.append(list(map(str, sys.stdin.readline().strip())))

M = [[float('inf')] * W for _ in range(H)]


def bfs(x1, y1, d):
    q = deque()
    q.append((d, x1, y1))

    while q:
        d, x1, y1 = q.popleft()

        M[x1][y1] = d

        if (x1 == xg - 1) and (y1 == yg - 1):
            break

        for dx, dy in ([0, 1], [1, 0], [0, -1], [-1, 0]):
            k = 1
            while k <= K:
                x2 = x1 + dx * k
                y2 = y1 + dy * k
                if x2 < 0 or x2 >= H:
                    break
                if y2 < 0 or y2 >= W:
                    break
                if m[x2][y2] == '@':
                    break
                if M[x2][y2] < d + 1:
                    break

                q.append((d + 1, x2, y2))

                k += 1


if m[xs - 1][ys - 1] != '@':
    bfs(xs - 1, ys - 1, 0)

# for i in range(len(M)):
#     print(M[i])


ans = M[xg - 1][yg - 1]
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

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


def solve():
    H, W, K = map(int, input().split())
    y1, x1, y2, x2 = map(int, input().split())
    l = [[1 if s=="@" else 0 for s in input()] for _ in range(H)]
    INF = 10**12

    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1

    ddy = [0, 0, -1, 1]
    ddx = [-1, 1, 0, 0]

    dist = defaultdict(lambda :INF)
    dist[(y1, x1)] = 0
    q = deque([(y1, x1)])

    while q:
        y, x = q.popleft()
        for i, (dy, dx) in enumerate(zip(ddy, ddx)):
            for j in range(1, K+1):
                if not (0<=y+dy*j<H and 0<=x+dx*j<W):
                    continue
                if l[y+dy*j][x+dx*j]:
                    break

                if dist[(y+dy*j, x+dx*j)] > dist[(y, x)] + 1:
                    dist[(y+dy*j, x+dx*j)] = dist[(y, x)] + 1
                    q.append((y+dy*j, x+dx*j))


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


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

he,w,k = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
l = [list(input()) for i in range(he)]

sx -= 1
sy -= 1
gx -= 1
gy -= 1
q = deque([])
d = [[float("INF")]*w for i in range(he)]

d[sx][sy] = 0
q.append((0,sx,sy))
while q:
    dis,bx,by = q.popleft()
    if bx == gx and by == gy:
        print(d[gx][gy])
        exit()
    for i in range(1,k+1):
        if 0 <= bx+i < he and l[bx+i][by] != "@":
            if d[bx+i][by] > dis+1:
                d[bx+i][by] = dis+1
                q.append((dis+1,bx+i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= bx-i < he and l[bx-i][by] != "@":
            if d[bx-i][by] > dis+1:
                d[bx-i][by] = dis+1
                q.append((dis+1,bx-i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by+i < w and l[bx][by+i] != "@":
            if d[bx][by+i] > dis+1:
                d[bx][by+i] = dis+1
                q.append((dis+1,bx,by+i))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by-i < w and l[bx][by-i] != "@":
            if d[bx][by-i] > dis+1:
                d[bx][by-i] = dis+1
                q.append((dis+1,bx,by-i))
        else:
            break

if d[gx][gy] == float("INF"):
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

he,w,k = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
l = [list(input()) for i in range(he)]

sx -= 1
sy -= 1
gx -= 1
gy -= 1
q = deque([])
d = [[float("INF")]*w for i in range(he)]

d[sx][sy] = 0
q.append((0,sx,sy))
while q:
    dis,bx,by = q.popleft()
    if bx == gx and by == gy:
        continue
    for i in range(1,k+1):
        if 0 <= bx+i < he and l[bx+i][by] != "@":
            if d[bx+i][by] > dis+1:
                d[bx+i][by] = dis+1
                q.append((dis+1,bx+i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= bx-i < he and l[bx-i][by] != "@":
            if d[bx-i][by] > dis+1:
                d[bx-i][by] = dis+1
                q.append((dis+1,bx-i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by+i < w and l[bx][by+i] != "@":
            if d[bx][by+i] > dis+1:
                d[bx][by+i] = dis+1
                q.append((dis+1,bx,by+i))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by-i < w and l[bx][by-i] != "@":
            if d[bx][by-i] > dis+1:
                d[bx][by-i] = dis+1
                q.append((dis+1,bx,by-i))
        else:
            break

if d[gx][gy] == float("INF"):
    print(-1)
else:
    print(d[gx][gy])

Submission status: Time Limit Exceeded

Solution code:
import heapq

he,w,k = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
l = [list(input()) for i in range(he)]

sx -= 1
sy -= 1
gx -= 1
gy -= 1
h = []
d = [[float("INF")]*w for i in range(he)]

d[sx][sy] = 0
heapq.heappush(h,(0,sx,sy))
while h:
    dis,bx,by = heapq.heappop(h)
    if bx == gx and by == gy:
        continue
    for i in range(1,k+1):
        if 0 <= bx+i < he and l[bx+i][by] != "@":
            if d[bx+i][by] > dis+1:
                d[bx+i][by] = dis+1
                heapq.heappush(h,(dis+1,bx+i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= bx-i < he and l[bx-i][by] != "@":
            if d[bx-i][by] > dis+1:
                d[bx-i][by] = dis+1
                heapq.heappush(h,(dis+1,bx-i,by))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by+i < w and l[bx][by+i] != "@":
            if d[bx][by+i] > dis+1:
                d[bx][by+i] = dis+1
                heapq.heappush(h,(dis+1,bx,by+i))
        else:
            break
    for i in range(1,k+1):
        if 0 <= by-i < w and l[bx][by-i] != "@":
            if d[bx][by-i] > dis+1:
                d[bx][by-i] = dis+1
                heapq.heappush(h,(dis+1,bx,by-i))
        else:
            break

if d[gx][gy] == float("INF"):
    print(-1)
else:
    print(d[gx][gy])

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    import queue
    input=sys.stdin.readline

    h,w,k=map(int,input().split())
    sy,sx,gy,gx=map(int,input().split())

    #maze=[]
    #for _ in range(h):
    #    maze.append(tuple(input()))

    maze=[tuple(input()) for _ in range(h)]

    sy-=1
    sx-=1
    gy-=1
    gx-=1

    #maze[sy][sx]="S"

    dis=[[-1]*w for _ in range(h)]
    dis[sy][sx]=0
    
    d= queue.Queue()
    d.put((sx,sy))
    #d = deque([(sx,sy)])
    #print(d)
    while not d.empty():
        (x,y)=d.get()
        #print(x,y)
        if x==gx and y==gy:
            print(dis[gy][gx])
            #maze[gy][gx]="G"

            #pri(dis)
            #pri(maze)

            exit()

        for (mx,my) in ((0,1),(1,0),(-1,0),(0,-1)):
            #print(mx,my,d)
            for j in range(1,k+1):
                nx=x+mx*j
                ny=y+my*j
                #print(y,x,">>",ny,nx)
                if 0<=nx<w and 0<=ny<h:
                    if maze[ny][nx]=="." and (dis[ny][nx]==-1 or dis[ny][nx]==dis[y][x]+1):
                        dis[ny][nx]=dis[y][x]+1
                        d.put((nx,ny))
                        #pri(dis)
                    else:
                        break
                else:
                    break

    print(-1)
        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    from collections import deque
    input=sys.stdin.readline

    h,w,k=map(int,input().split())
    sy,sx,gy,gx=map(int,input().split())

    #maze=[]
    #for _ in range(h):
    #    maze.append(tuple(input()))

    maze=[tuple(input()) for _ in range(h)]

    sy-=1
    sx-=1
    gy-=1
    gx-=1

    #maze[sy][sx]="S"

    dis=[[-1]*w for _ in range(h)]



    dis[sy][sx]=0



    d = deque([(sx,sy)])
    while len(d)>0:
        (x,y)=d.popleft()
        if x==gx and y==gy:
            print(dis[gy][gx])
            #maze[gy][gx]="G"

            #pri(dis)
            #pri(maze)

            exit()

        for (mx,my) in ((0,1),(1,0),(-1,0),(0,-1)):
            #print(mx,my,d)
            for j in range(1,k+1):
                nx=x+mx*j
                ny=y+my*j
                #print(y,x,">>",ny,nx)
                if 0<=nx<w and 0<=ny<h:
                    if maze[ny][nx]=="." and (dis[ny][nx]==-1 or dis[ny][nx]==dis[y][x]+1):
                        dis[ny][nx]=dis[y][x]+1
                        d.append((nx,ny))
                        #pri(dis)
                    else:
                        break
                else:
                    break

    print(-1)
        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input=sys.stdin.readline

    h,w,k=map(int,input().split())
    sy,sx,gy,gx=map(int,input().split())

    maze=[]
    for _ in range(h):
        maze.append(tuple(input()))

    #maze=[list(input()) for _ in range(h)]

    sy-=1
    sx-=1
    gy-=1
    gx-=1

    #maze[sy][sx]="S"

    dis=[[-1]*w for _ in range(h)]

    from collections import deque

    dis[sy][sx]=0



    d = deque([(sx,sy)])
    while len(d)>0:
        (x,y)=d.popleft()
        if x==gx and y==gy:
            print(dis[gy][gx])
            #maze[gy][gx]="G"

            #pri(dis)
            #pri(maze)

            exit()

        for (mx,my) in ((0,1),(1,0),(-1,0),(0,-1)):
            #print(mx,my,d)
            for j in range(1,k+1):
                nx=x+mx*j
                ny=y+my*j
                #print(y,x,">>",ny,nx)
                if 0<=nx<w and 0<=ny<h:
                    if maze[ny][nx]=="." and (dis[ny][nx]==-1 or dis[ny][nx]==dis[y][x]+1):
                        dis[ny][nx]=dis[y][x]+1
                        d.append((nx,ny))
                        #pri(dis)
                    else:
                        break
                else:
                    break

    print(-1)
        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
inf=1000002
sys.setrecursionlimit(inf)
from collections import deque
h,w,k=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
c=[input() for i in range(h)]
dp=[[inf if c[i][j]=="." else -1 for j in range(w)] for i in range(h)]
now=deque()
now.append([x2-1,y2-1])
#kの更新が遅い
def bfs(d):
    global h,w,k,dp,now,x2,y2
    l=len(now)
    if l==0:
        return
    for i in range(l):
        x,y=now.popleft()
        for j in range(1,min(k+1,w-y)):
            if dp[x][y+j]==inf:
                dp[x][y+j]=d
                now.append([x,y+j])
            if dp[x][y+j]==-1:
                break
        for j in range(1,min(k+1,y+1)):
            if dp[x][y-j]==inf:
                dp[x][y-j]=d
                now.append([x,y-j])
            if dp[x][y-j]==-1:
                break
        for j in range(1,min(k+1,h-x)):
            if dp[x+j][y]==inf:
                dp[x+j][y]=d
                now.append([x+j,y])
            if dp[x+j][y]==-1:
                break
        for j in range(1,min(k+1,x+1)):
            if dp[x-j][y]==inf:
                dp[x-j][y]=d
                now.append([x-j,y])
            if dp[x-j][y]==-1:
                break
    bfs(d+1)
bfs(1)
print(dp[x1-1][y1-1] if dp[x1-1][y1-1]!=inf else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
dxdy = ((-1,0), (1,0), (0,-1), (0,1)) # タプルやリストで持っておくと便利

H, W, K = map(int,input().split())
x1, y1, x2, y2 = map(int,input().split())
mp = [input() for _ in range(H)]
INF = 10**10
dist = [[INF]*W for _ in range(H)]
dist[x1-1][y1-1] = 0
q = deque()
q.append((x1-1,y1-1)) # スタート地点をenqueue
while(q):
    x, y = q.popleft()
    if x==x2-1 and y==y2-1:
        print (dist[x2-1][y2-1])
        exit()
    else:
        for dx, dy in  dxdy:
            for i in range(1,K+1):
                nx = x + dx*i
                ny = y + dy*i
                if not (0<=nx<H and 0<=ny<W) or mp[nx][ny]=='@':
                    break
                if dist[nx][ny] == INF:
                    q.append((nx,ny))
                dist[nx][ny] = min(dist[nx][ny], dist[x][y] + 1)
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heapify, heappop, heappush

def solve():
    input = sys.stdin.readline
    H, W, K = map(int, input().split())
    a, b, x, y = map(int, input().split())
    a -= 1
    b -= 1
    x -= 1
    y -= 1
    C = [input().strip("\n") for _ in range(H)]
    D = [[10 ** 7 for _ in range(W)] for h in range(H)]
    D[a][b] = 0
    q = []
    heapify(q)
    for h in range(a):
        #up
        if C[a-h-1][b] == "@": break
        else: heappush(q, (h // K + 1, a - h - 1, b, "ud"))
    for h in range(H-a-1):
        #down
        if C[a + h + 1][b] == "@": break
        else: heappush(q, (h // K + 1, a + h + 1, b, "ud"))
    for w in range(b):
        if C[a][b-w-1] == "@": break
        else: heappush(q, (w//K + 1, a, b-w-1, "lr"))
    for w in range(W - b - 1):
        if C[a][b+w+1] == "@": break
        else: heappush(q, (w//K + 1, a, b+w+1, "lr"))

    while q:
        d, h, w, direc = heappop(q)
        if D[h][w] == 10 ** 7:
            if h == x and w == y:
                print(d)
                break
            D[h][w] = d
            if direc == "lr": #udのみ
                for dh in range(h):
                    if C[h-dh-1][w] == "@": break
                    elif D[h-dh-1][w] <= d: break
                    heappush(q, (dh//K + d + 1, h-dh-1, w, "ud"))
                for dh in range(H-h-1):
                    if C[h+dh+1][w] == "@": break
                    elif D[h+dh+1][w] <= d: break
                    heappush(q, (dh//K + d + 1, h+dh+1, w, "ud"))
            else:
                for dw in range(w):
                    if C[h][w-dw-1] == "@": break
                    elif D[h][w-dw-1] <= d: break
                    heappush(q, (dw//K + d + 1, h, w-dw-1, "lr"))
                for dw in range(W-w-1):
                    if C[h][w+dw+1] == "@": break
                    elif D[h][w+dw+1] <= d: break
                    heappush(q, (dw//K + d + 1, h, w+dw+1, "lr"))
    else: print(-1)
    #print(D)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
from collections import deque
sys.setrecursionlimit(10 ** 8)
 
H, W, K = map(int, sys.stdin.readline().strip().split())
xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())
 
m = []
for _ in range(H):
    m.append(list(map(str, sys.stdin.readline().strip())))
 
M = [[float('inf')] * W for _ in range(H)]
 
 
def bfs(x1, y1, d):
    q = deque()
    # heapq.heapify(q)
    # heapq.heappush(q, (d, (x1, y1)))
    q.append((d, (x1, y1)))
 
    while q:
        # d, u = heapq.heappop(q)
        d, u = q.popleft()
        x1 = u[0]
        y1 = u[1]
 
        M[x1][y1] = d
 
        if (x1 == xg - 1) and (y1 == yg - 1):
            break
 
        for dx, dy in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
            k = 1
            while k <= K:
                x2 = x1 + dx * k
                y2 = y1 + dy * k
                if x2 < 0 or x2 >= H:
                    break
                if y2 < 0 or y2 >= W:
                    break
                if m[x2][y2] == '@':
                    break
                if M[x2][y2] != float('inf'):
                    break
 
                # heapq.heappush(q, (d + 1, (x2, y2)))
                q.append((d + 1, (x2, y2)))
 
                k += 1
 
 
if m[xs - 1][ys - 1] != '@':
    bfs(xs - 1, ys - 1, 0)
 
# for i in range(len(M)):
#     print(M[i])
 
 
ans = M[xg - 1][yg - 1]
if ans == float('inf'):
    print(-1)
else:
    print(ans)

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] * W for _ in range(H)]
# pathD = [[INF] * W for _ in range(H)]
path[x1][y1] = 0
# pathD[x1][y1] = 0

q = deque()
q.append((x1, y1, 0, 0, 0))
D = ((0, 1), (1, 0), (0, -1), (-1, 0))
q_append = q.append
q_appendleft = q.appendleft
while q:
    x, y, d, k, s = q.popleft()
    if k == 0:
        for nd in range(4):
            dx, dy = D[nd]
            nx = x + dx; ny = y + dy
            if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == '.' and path[nx][ny] >= s + 1:
                path[nx][ny] = s + 1
                q.append((nx, ny, nd, K - 1, s + 1))
    else:
        for nd in range(4):
            dx, dy = D[nd]
            nx = x + dx; ny = y + dy
            ns = s + (d != nd)
            if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == '.' and path[nx][ny] >= ns:
                path[nx][ny] = ns
                nk = k - 1 if d == nd else K - 1
                appendQ = q_appendleft if d == nd else q_append
                appendQ((nx, ny, nd, nk, ns))

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