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


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, y1] == [xg, yg]:
            print(d)
            return

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

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if m[x2][y2] == '@':
                        break
                    elif M[x2][y2] == -1:
                        q.append((d + 1, x2, y2))
                    elif M[x2][y2] == d + 1:
                        continue
                    else:
                        break

    print(-1)


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


if __name__ == '__main__':
    H, W, K = map(int, sys.stdin.readline().strip().split())
    xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())
    xg -= 1
    yg -= 1

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

    M = [[-1] * W for _ in range(H)]

    bfs(xs - 1, ys - 1, 0)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


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, y1] == [xg, yg]:
            print(d)
            return

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

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if m[x2][y2] == '@':
                        break
                    elif M[x2][y2] == -1:
                        q.append((d + 1, x2, y2))
                    elif M[x2][y2] == d + 1:
                        continue
                    else:
                        break

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


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


if __name__ == '__main__':
    H, W, K = map(int, sys.stdin.readline().strip().split())
    xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())
    xg -= 1
    yg -= 1

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

    M = [[-1] * W for _ in range(H)]

    bfs(xs - 1, ys - 1, 0)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


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, y1] == [xg, yg]:
            print(d)
            return

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

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if (m[x2][y2] == '@') or (M[x2][y2] < d + 1):
                        break
                    elif M[x2][y2] == d + 1:
                        continue

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


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


if __name__ == '__main__':
    H, W, K = map(int, sys.stdin.readline().strip().split())
    xs, ys, xg, yg = map(int, sys.stdin.readline().strip().split())
    xg -= 1
    yg -= 1

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

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

    bfs(xs - 1, ys - 1, 0)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


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):
            print(d)
            return

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

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if (m[x2][y2] == '@') or (M[x2][y2] < d + 1):
                        break
                    elif M[x2][y2] == d + 1:
                        continue

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


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


if __name__ == '__main__':
    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)]

    bfs(xs - 1, ys - 1, 0)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


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):
            print(d)
            return

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

                if (0 <= x2 < H) and (0 <= y2 < W):
                    if (m[x2][y2] == '@') or (M[x2][y2] < d + 1):
                        break
                    elif M[x2][y2] == d + 1:
                        continue

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


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


if __name__ == '__main__':
    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)]

    bfs(xs - 1, ys - 1, 0)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


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):
            print(d)
            return
        
        for dx, dy in ([0, 1], [1, 0], [0, -1], [-1, 0]):
            for k in range(1, K + 1):
                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))
    print(-1)


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

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


if __name__ == '__main__':
    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)]
    
    bfs(xs - 1, ys - 1, 0)

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]):
            for k in range(1, K + 1):
                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))


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
                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 heapq
H,W,K = map(int,input().split())
s1,e1,s2,e2 = map(int,input().split())
s1-=1
e1-=1
s2-=1
e2-=1
L = []
board = []
for _ in range(H):
    a = input()
    L.append(a)
for i in range(H):
    l = L[i]
    tmp = []
    for j in range(len(l)):
        tmp.append(l[j])
    board.append(tmp)

hq = []
heapq.heappush(hq,[0,s1,e1])
seen = [[False]*(W) for _ in range(H)]
destination = [(1,0),(-1,0),(0,1),(0,-1)]
while hq:
    cost,x,y = heapq.heappop(hq)
    seen[x][y] = True
    if x==s2 and y ==e2:
        print(cost);exit()
        break
    for dx,dy in destination:
        X,Y = x,y
        for i in range(K):
            X +=dx
            Y += dy
            if 0>X or X>=H or 0>Y or Y>=W: break
            else:
                if board[X][Y]=='@':
                    break
                elif not seen[X][Y]:
                    heapq.heappush(hq,[cost+1,X,Y])
                    seen[X][Y] = True

print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
import heapq

def main():
  h, w, k = map(int, input().split())
  x1, y1, x2, y2 = map(lambda x:int(x)-1, input().split())
  S = [input().rstrip() for _ in range(h)]
  dist = [[[float("inf")]*w  for i in range(h)] for _ in range(4)]
  que = []
  que.append((0, 0, x1, y1))
  dist[0][x1][y1] = 0

  while que:
    c, di, x, y = heapq.heappop(que)
    if dist[di][x][y] < c:
      continue
    l, r = c+1, -(-c//k)*k
    if di == 0:
      if x > 0 and S[x-1][y] == "." and dist[di][x-1][y] > l:
        dist[di][x-1][y] = l
        heapq.heappush(que, (l, di, x-1, y))
    elif di == 1:
      if y > 0 and S[x][y-1] == "." and dist[di][x][y-1] > l:
        dist[di][x][y-1] = l
        heapq.heappush(que, (l, di, x, y-1))
    elif di == 2:
      if x < h-1 and S[x+1][y] == "." and dist[di][x+1][y] > l:
        dist[di][x+1][y] = l
        heapq.heappush(que, (l, di, x+1, y))
    else:
      if y < w-1 and S[x][y+1] == "." and dist[di][x][y+1] > l:
        dist[di][x][y+1] = l
        heapq.heappush(que, (l, di, x, y+1))

    if di%2:
      if dist[0][x][y] > r:
        dist[0][x][y] = r
        heapq.heappush(que, (r, 0, x, y))
      if dist[2][x][y] > r:
        dist[2][x][y] = r
        heapq.heappush(que, (r, 2, x, y))

    else:
      if dist[1][x][y] > r:
        dist[1][x][y] = r
        heapq.heappush(que, (r, 1, x, y))
      if dist[3][x][y] > r:
        dist[3][x][y] = r
        heapq.heappush(que, (r, 3, x, y))
  t = min(dist[0][x2][y2], dist[1][x2][y2], dist[2][x2][y2], dist[3][x2][y2])
  if t == float("inf"):
    print(-1)
  else:
    ans = -(-t//k)
    print(ans)

if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
import heapq

h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(lambda x:int(x)-1, input().split())
S = [input().rstrip() for _ in range(h)]
dist = [[[float("inf")]*w  for i in range(h)] for _ in range(4)]
que = []
que.append((0, 0, x1, y1))
dist[0][x1][y1] = 0
  
while que:
  c, di, x, y = heapq.heappop(que)
  if x == x2 and y == y2:
    break
  if dist[di][x][y] < c:
    continue
  l, r = c+1, -(-c//k)*k
  if di == 0:
    if x > 0 and S[x-1][y] == "." and dist[di][x-1][y] > l:
      dist[di][x-1][y] = l
      heapq.heappush(que, (l, di, x-1, y))
  elif di == 1:
    if y > 0 and S[x][y-1] == "." and dist[di][x][y-1] > l:
      dist[di][x][y-1] = l
      heapq.heappush(que, (l, di, x, y-1))
  elif di == 2:
    if x < h-1 and S[x+1][y] == "." and dist[di][x+1][y] > l:
      dist[di][x+1][y] = l
      heapq.heappush(que, (l, di, x+1, y))
  else:
    if y < w-1 and S[x][y+1] == "." and dist[di][x][y+1] > l:
      dist[di][x][y+1] = l
      heapq.heappush(que, (l, di, x, y+1))
      
  if di%2:
    if dist[0][x][y] > r:
      dist[0][x][y] = r
      heapq.heappush(que, (r, 0, x, y))
    if dist[2][x][y] > r:
      dist[2][x][y] = r
      heapq.heappush(que, (r, 2, x, y))
    
  else:
    if dist[1][x][y] > r:
      dist[1][x][y] = r
      heapq.heappush(que, (r, 1, x, y))
    if dist[3][x][y] > r:
      dist[3][x][y] = r
      heapq.heappush(que, (r, 3, x, y))
t = min(dist[0][x2][y2], dist[1][x2][y2], dist[2][x2][y2], dist[3][x2][y2])
if t == float("inf"):
  print(-1)
else:
  ans = -(-t//k)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
import heapq

h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(lambda x:int(x)-1, input().split())
S = [input().rstrip() for _ in range(h)]
dist = [[[float("inf")]*w  for i in range(h)] for _ in range(4)]
que = []
que.append((0, 0, x1, y1))
dist[0][x1][y1] = 0
  
while que:
  c, di, x, y = heapq.heappop(que)
  if dist[di][x][y] < c:
    continue
  l, r = c+1, -(-c//k)*k
  if di == 0:
    if x > 0 and S[x-1][y] == "." and dist[di][x-1][y] > l:
      dist[di][x-1][y] = l
      heapq.heappush(que, (l, di, x-1, y))
  elif di == 1:
    if y > 0 and S[x][y-1] == "." and dist[di][x][y-1] > l:
      dist[di][x][y-1] = l
      heapq.heappush(que, (l, di, x, y-1))
  elif di == 2:
    if x < h-1 and S[x+1][y] == "." and dist[di][x+1][y] > l:
      dist[di][x+1][y] = l
      heapq.heappush(que, (l, di, x+1, y))
  else:
    if y < w-1 and S[x][y+1] == "." and dist[di][x][y+1] > l:
      dist[di][x][y+1] = l
      heapq.heappush(que, (l, di, x, y+1))
      
  if di%2:
    if dist[0][x][y] > r:
      dist[0][x][y] = r
      heapq.heappush(que, (r, 0, x, y))
    if dist[2][x][y] > r:
      dist[2][x][y] = r
      heapq.heappush(que, (r, 2, x, y))
    
  else:
    if dist[1][x][y] > r:
      dist[1][x][y] = r
      heapq.heappush(que, (r, 1, x, y))
    if dist[3][x][y] > r:
      dist[3][x][y] = r
      heapq.heappush(que, (r, 3, x, y))
t = min(dist[0][x2][y2], dist[1][x2][y2], dist[2][x2][y2], dist[3][x2][y2])
if t == float("inf"):
  print(-1)
else:
  ans = -(-t//k)
  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(int, input().split())

c = [input().rstrip() for _ in range(H)]

d = deque([(0, x1-1, y1-1)])

dp = [[False] * W for _ in range(H)]
dp[x1-1][y1-1] = True

while d:
    step, x, y = d.popleft()
    if x == x2-1 and y == y2-1:
        print(step)
        break

    for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        for i in range(1, K+1):
            nx = x + dx * i
            ny = y + dy * i
            if 0 <= nx < H and 0 <= ny < W:
                if c[nx][ny] == '@':
                    break

                if not dp[nx][ny]:
                    dp[nx][ny] = True
                    d.append((step + 1, nx, ny))
            else:
                break
else:
    print(-1)

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 in range(4):
            dx = ddx[i]
            dy = ddy[i]
            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))
                else:
                    break


    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

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

c = [input().rstrip() for _ in range(H)]

d = deque([(0, x1-1, y1-1)])
dp = [[False] * W for _ in range(H)]

while d:
    step, x, y = d.popleft()
    if x == x2-1 and y == y2-1:
        print(step)
        break

    for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        for i in range(1, K+1):
            nx = x + dx * i
            ny = y + dy * i
            if 0 <= nx < H and 0 <= ny < W:
                if c[nx][ny] == '@':
                    break

                if not dp[nx][ny]:
                    dp[nx][ny] = True
                    d.append((step + 1, nx, ny))
            else:
                break
else:
    print(-1)

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 in range(4):
            dx = ddx[i]
            dy = ddy[i]
            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:
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 dy, dx in 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:
from collections import deque

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

c = []
for i in range(H):
    c.append(input().rstrip())

d = deque([(0, x1-1, y1-1)])

dp = [[False] * W for _ in range(H)]


def check(step, x, y):
    if c[x][y] == '@':
        return False

    if not dp[x][y]:
        dp[x][y] = True
        d.append((step + 1, x, y))

    return True


while d:
    step, x, y = d.popleft()
    if x == x2-1 and y == y2-1:
        print(step)
        break

    for i in range(x+1, min(x+K+1, H)):
        if not check(step, i, y):
            break

    for i in range(x-1, max(-1, x-K-1), -1):
        if not check(step, i, y):
            break

    for j in range(y+1, min(y+K+1, W)):
        if not check(step, x, j):
            break

    for j in range(y-1, max(-1, y-K-1), -1):
        if not check(step, x, j):
            break
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from heapq import heappop, heappush
def resolve():
    m, n, k = map(int, input().split())
    si, sj, ti, tj = map(lambda x : int(x) - 1, input().split())
    grid = [input() for _ in range(m)]
    dist = [[[(INF, 0)] * 4 for _ in range(n)] for _ in range(m)]
    heap = []
    for i in range(4):
        dist[si][sj][i] = (0, 0)
        heappush(heap, (0, 0, si, sj, i))

    D = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while heap:
        d, r, i, j, dir = heappop(heap)
        if dist[i][j][dir] != (d, r):
            continue
        # change direction
        for ndir in range(4):
            nd = (d + (r > 0), 0)
            if dist[i][j][ndir] > nd:
                dist[i][j][ndir] = nd
                heappush(heap, (nd[0], nd[1], i, j, ndir))
        # move to forth
        di, dj = D[dir]
        ni, nj = i + di, j + dj
        if not (0 <= ni < m and 0 <= nj < n):
            continue
        if grid[ni][nj] == '@':
            continue
        nd = (d + 1, 0) if r == k - 1 else (d, r + 1)
        if dist[ni][nj][dir] > nd:
            dist[ni][nj][dir] = nd
            heappush(heap, (nd[0], nd[1], ni, nj, dir))

    ans = INF
    for dir in range(4):
        d, r = dist[ti][tj][dir]
        ans = min(ans, d + (r > 0))
    if ans == INF:
        ans = -1
    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf=10**9
    h,w,k=MI()
    x1,y1,x2,y2=MI1()
    aa=[[0 if c=="@" else inf for c in SI()] for _ in range(h)]
    #p2D(aa)

    aa[x1][y1]=0
    q=deque()
    q.append((x1,y1,0))
    while q:
        x,y,d=q.popleft()
        for nx in range(x+1,min(x+k+1,h)):
            if aa[nx][y]<d+1:break
            aa[nx][y]=d+1
            q.append((nx,y,d+1))
        for nx in range(x-1,max(x-k-1,-1),-1):
            if aa[nx][y]<d+1:break
            aa[nx][y]=d+1
            q.append((nx,y,d+1))
        for ny in range(y+1,min(y+k+1,w)):
            if aa[x][ny]<d+1:break
            aa[x][ny]=d+1
            q.append((x,ny,d+1))
        for ny in range(y-1,max(y-k-1,-1),-1):
            if aa[x][ny]<d+1:break
            aa[x][ny]=d+1
            q.append((x,ny,d+1))
        #p2D(aa)
        #print()

    ans=aa[x2][y2]
    if ans==inf:print(-1)
    else:print(ans)

main()

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)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
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(4):
        for j in range(1,k+1):
            nx = bx+dx[i]*j
            ny = by+dy[i]*j
            if 0 > nx or 0 > ny or nx >= he  or ny >= w:
                break
            if l[nx][ny] == "@":
                break
            if d[nx][ny] <= dis:
                break
            if d[nx][ny] > dis+1:
                d[nx][ny] = dis+1
                q.append((dis+1,nx,ny))

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

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] != "@" and d[bx+i][by] > dis:
            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] != "@" and d[bx-i][by] > dis:
            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] != "@" and d[bx][by+i] > dis:        
            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] != "@" and d[bx][by-i] > dis:
            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])