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:

class BFS:
    def __init__(self,H, W,  K, start, goal, data):
        self.depth = 0
        self.next_search = [start]
        self.covered = set()
        self.current_pos = start
        self.goal = goal
        self.start = start
        self.ans = None
        self.data = data
        self.K = K
        self.H = H
        self.W = W
    def solve(self):
        if self.isStartGoal():
            return 0

        MAX = 10**6
        for i in range(MAX):
            if self.DoesStop():
                return self.ans
            if not self.next_search:
                return -1
        return -1

    def isStartGoal(self):
        if self.isGoal(self.start):
            return True
        return False

    def isGoal(self, pos):
        if self.goal == pos:
            return True
        else:
            return False

    def isValidRange(self, x, y):
        if x >= 0 and x < self.H:
            if y>=0 and y < self.W:
                return True
        return False

    def getNextCandidates(self, cur):
        i, j = cur
        next_candidates = []
        for delta in range(1, self.K+1):
            if not self.isValidRange(i,j+delta):
                break
            if not self.data[i][j + delta] == ".":
                break
            next_candidates.append((i, j+delta))
        for delta in range(1, self.K+1):
            if not self.isValidRange(i,j-delta):
                break
            if not self.data[i][j - delta] == ".":
                break
            next_candidates.append((i, j-delta))
        for delta in range(1, self.K+1):
            if not self.isValidRange(i+delta, j):
                break
            if not self.data[i+delta][j] == ".":
                break
            next_candidates.append((i+delta, j))
        for delta in range(1, self.K +1 ):
            if not self.isValidRange(i-delta, j):
                break
            if not self.data[i-delta][j] == ".":
                break
            next_candidates.append((i-delta, j))
        return next_candidates

    def DoesStop(self):
        self.depth += 1
        self.current_pos  = self.next_search
        self.next_search = []

        for cur in self.current_pos:
            next_candidates = self.getNextCandidates(cur)
            for next_pos in next_candidates:
                if self.isGoal(next_pos):
                    self.ans = self.depth
                    return True
                if next_pos not in self.covered:
                    self.covered.add(next_pos)
                    self.next_search.append(next_pos)
        return False

H, W, K = map(int,input().split())
a,b,c,d = map(int,input().split())
data = []

for i in range(H):
    l=list(input())
    data.append(l)


bfs = BFS(H, W,  K, (a-1,b-1), (c-1,d-1), data)
print(bfs.solve())

Submission status: Time Limit Exceeded

Solution code:
h,w,k = map(int, input().split())
sx,sy,gx,gy = map(int, input().split())
sx-=1
sy-=1
gx-=1
gy-=1

grid = ['' for _ in range(h)]

for i in range(h):
    grid[i] = input()
INF = 1001001001001001001  
costgrid = [[INF]*w for _ in range(h)]

import heapq

q = []
q.append((0,sx,sy))

dx = (0,1,0,-1)
dy = (1,0,-1,0)
ans=INF
while q:
    cost,x,y = heapq.heappop(q)
    for i in range(4):
        for j in range(1,k+1):
            nx = x+dx[i]*j
            ny = y+dy[i]*j
            if(not 0<=nx<h):
                break
            if(not 0<=ny<w):
                break
            if(grid[nx][ny]=='@'):
                break
            if(costgrid[nx][ny]<=cost+1):
                continue
            costgrid[nx][ny]=min(costgrid[nx][ny],cost+1)
            heapq.heappush(q,(cost+1,nx,ny))
            if nx==gx and ny==gy:
                ans=min(costgrid[nx][ny],ans)
                q=[]

if ans!=INF:
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h, w, k = map(int, input().split())
y1, x1, y2, x2 = map(int, input().split())
x1 -= 1
x2 -= 1
y1 -= 1
y2 -= 1

c = []
for _ in range(h):
    c.append(list(input()))
check = [[False for _ in range(w)] for _ in range(h)]
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

queue = deque()
queue.append([x1, y1, 0])
while queue:
    pos = queue.popleft()
    ans = pos[2] + 1
    for dx, dy in directions:
        next_x = pos[0]
        next_y = pos[1]
        for _ in range(1, k + 1):
            next_x += dx
            next_y += dy
            if next_x == -1 or next_x == w or next_y == -1 or next_y == h:
                break
            if check[next_y][next_x]:
                continue
            if c[next_y][next_x] == "@":
                break
            check[next_y][next_x] = True
            if next_y == y2 and next_x == x2:
                print(ans)
                exit()
            queue.append([next_x, next_y, ans])

print(-1)

Submission status: Time Limit Exceeded

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

H,W,K = map(int,readline().split())
x1,y1,x2,y2 = map(int,readline().split())
x1,y1,x2,y2 = x1 - 1,y1 - 1,x2 - 1,y2 - 1

grid = [None] * H
for i in range(H):
  grid[i] = readline().rstrip()
  
# 操作としてあり得るのは、
# ・1かきでKマス進む or @の直前まで進む
# ・1かきでKマス未満進んで方向転換する
# 
# ・前回水をかいてから何マス進んでいるか
# ・前回水をかいて、どのむき(U,D,L,R)に進んでいるか
#  (来たところに戻ることはあり得ないので)
# ・今までに何回水をかいたか
# ・今どこにいるか
# 水かき回数でダイクストラ
# たとえ泳ぐ向きが違っても同じ場所を2回通ることはあり得ない。

import numpy as np
# from numba import njit,i8
from collections import defaultdict

import heapq
# 今まで何回水をかいたか,i,j,前回水をかいてから何マス進んでいるか,どのむきに進んでいるか
def solve():
  def get_turn(d):
    if d in ("U","D"): # 縦方向に進んでいた場合の次の進み先
      return ((0,1,"R"),(0,-1,"L"))
    else:
      return ((1,0,"D"),(-1,0,"U"))
  
  def get_straight(d):
    if d == "U":
      return (-1,0,"U")
    if d == "D":
      return (1,0,"D")
    if d == "L":
      return (0,-1,"L")
    if d == "R":
      return (0,1,"R")
  q = []
  heapq.heapify(q)
  # 最初に進む4方向を入れておく
  seen = defaultdict(int)
  for first in "UDLR":
    c = get_straight(first)
    if 0 <= x1 + c[0] < H and 0 <= y1 + c[1] < W:
      if grid[x1 + c[0]][y1 + c[1]] != "@":
        heapq.heappush(q,(1,x1 + c[0],y1 + c[1],1,c[2]))
  seen[(x1,y1)] 
  while q:
    cost,i,j,swim,dire = heapq.heappop(q)
    #print("cost",cost,"i",i,"j",j,"swim",swim,"dire",dire)
    #print(q)
    if (i,j) in seen and seen[(i,j)] < cost:
      continue
    if i == x2 and j == y2:
      return cost
    seen[(i,j)] = cost
    # 曲がる場合
    cases = get_turn(dire)
    for c in cases:
      if 0 <= i + c[0] < H and 0 <= j + c[1] < W:
        if grid[i + c[0]][j + c[1]] != "@":
          heapq.heappush(q,(cost + 1,i + c[0],j + c[1],1,c[2]))
    # 直進する場合
    c = get_straight(dire)
    if swim < K: # まだKマス進んでいない
      if 0 <= i + c[0] < H and 0 <= j + c[1] < W:
        if grid[i + c[0]][j + c[1]] != "@":
          # コストは増えず、swim距離は増える
          heapq.heappush(q,(cost,i + c[0],j + c[1],swim + 1,c[2]))
    elif swim == K: # すでにKマス進んでいる場合
      # 直進する場合
      if 0 <= i + c[0] < H and 0 <= j + c[1] < W:
        if grid[i + c[0]][j + c[1]] != "@":
          # コストは増えて、swim距離は1に
          heapq.heappush(q,(cost + 1,i + c[0],j + c[1],1,c[2]))
  else:
    return -1
print(solve())

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
def main():
    h,w,k = map(int,input().split())
    x,y,gx,gy = map(int,input().split())
    x -= 1
    gx -= 1
    y -= 1
    gy -= 1
    c = [list(input()) for _ in range(h)]
    d = [[-1 for _ in range(w)] for _ in range(h)]
    dx = (1, 0, -1, 0)
    dy = (0, 1, 0, -1)
    que = []
    heappush(que,(0,(x,y)))
    d[x][y] = 0
    while que:
        [num,(qx,qy)] = heappop(que)
        if qx == gx and qy == gy:
            break
        for i in range(4):
            for K in range(1,k+1):
                nx = qx + dx[i]*K
                ny = qy + dy[i]*K
                if not(nx>=0 and h>nx and ny>=0 and w>ny) or c[nx][ny] == '@':
                    break
                if d[nx][ny] == -1 or d[nx][ny] > d[qx][qy]+1:
                    d[nx][ny] = d[qx][qy] + 1
                    heappush(que,[d[nx][ny],(nx,ny)])
    print(d[gx][gy])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import heapq
H,W,K = map(int,input().split())

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

c = []

for i in range(H):

    C = list(input())
    c.append(C)

u = [[(float("inf") , float("inf"))] * W for i in range(H)]
d = [[(float("inf") , float("inf"))] * W for i in range(H)]
l = [[(float("inf") , float("inf"))] * W for i in range(H)]
r = [[(float("inf") , float("inf"))] * W for i in range(H)]

q = []
heapq.heappush(q,(0,0,"l",x1,y1))
heapq.heappush(q,(0,0,"r",x1,y1))
heapq.heappush(q,(0,0,"u",x1,y1))
heapq.heappush(q,(0,0,"d",x1,y1))
u[x1][y1] = (0,0)
d[x1][y1] = (0,0)
l[x1][y1] = (0,0)
r[x1][y1] = (0,0)

end = 0
while len(q) > 0:

    tmp = heapq.heappop(q)
    kai,sus,di,x,y = tmp

    if end > 4*H*W+10:
        break

    if di == "l" and l[x][y] != (kai,sus):
        continue
    if di == "r" and r[x][y] != (kai,sus):
        continue
    if di == "u" and u[x][y] != (kai,sus):
        continue
    if di == "d" and d[x][y] != (kai,sus):
        continue

    end += 1

    if di == "l" and x != 0 and sus < K and c[x-1][y]!="@" :
        if l[x-1][y] > (kai,sus+1):
            l[x-1][y] = (kai,sus+1)
            q.append( (kai,sus+1,"l",x-1,y) )

    if di == "r" and x != H-1 and sus < K and c[x+1][y]!="@":
        if r[x+1][y] > (kai,sus+1):
            r[x+1][y] = (kai,sus+1)
            q.append( (kai,sus+1,"r",x+1,y) )

    if di == "u" and y != 0 and sus < K and c[x][y-1]!="@":
        if u[x][y-1] > (kai,sus+1):
            u[x][y-1] = (kai,sus+1)
            q.append( (kai,sus+1,"u",x,y-1) )

    if di == "d" and y != W-1 and sus < K and c[x][y+1]!="@":
        if d[x][y+1] > (kai,sus+1):
            d[x][y+1] = (kai,sus+1)
            q.append( (kai,sus+1,"d",x,y+1) )


    if x != 0:
        if l[x-1][y] > (kai+1,1) and c[x-1][y]!="@":
            l[x-1][y] = (kai+1,1)
            q.append( (kai+1,1,"l",x-1,y) )

    if x != H-1:
        if r[x+1][y] > (kai+1,1) and c[x+1][y]!="@":
            r[x+1][y] = (kai+1,1)
            q.append( (kai+1,1,"r",x+1,y) )

    if y != 0:
        if u[x][y-1] > (kai+1,1) and c[x][y-1]!="@":
            u[x][y-1] = (kai+1,1)
            q.append( (kai+1,1,"u",x,y-1) )

    if y != W-1:
        if d[x][y+1] > (kai+1,1) and c[x][y+1]!="@":
            d[x][y+1] = (kai+1,1)
            q.append( (kai+1,1,"d",x,y+1) )

ans = min(l[x2][y2],r[x2][y2],u[x2][y2],d[x2][y2])
if ans[0] == float("inf"):
    print (-1)
else:
    print (ans[0]+1)

#print (r)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from functools import lru_cache
h,w,k = map(int,input().split())
k = min(k,777)
sy,sx,gy,gx = map(int,input().split())
sy,sx,gy,gx = sy-1,sx-1,gy-1,gx-1
map = [str(input()) for i in range(h)]
gone = [[0] * w for i in range(h)]
now = deque()
now.append((sy,sx,-1))
gone[sy][sx] = 1
if map[gy][gx] == "@":
    print(-1)
    exit()
for ans in range(10 ** 6+1):
    next = deque()
    while now:
        y,x,status = now.popleft()
        if y == gy and x == gx:
            print(ans)
            exit()
        if status != 0 or (y>0 and map[y-1][x] != "@"):
            for i in range(1,k+1):
                if y-i < 0 or map[y-i][x] == "@":
                    break
                else:
                    if gone[y-i][x] == 0:
                        gone[y-i][x] = 1
                        next.append((y-i,x,0))
        if status != 1 or (y<h-1 and map[y+1][x] != "@"):
            for i in range(1,k+1):
                if y +i >= h or map[y+i][x] == "@":
                    break
                else:
                    if gone[y + i][x] == 0:
                        gone[y + i][x] = 1
                        next.append((y+i,x,1))
        if status != 2 or (x>0 and map[y][x-1] != "@"):
            for i in range(1,k+1):
                if x - i < 0 or map[y][x-i] == "@":
                    break
                else:
                    if gone[y][x-i] == 0:
                        gone[y][x-i] = 1
                        next.append((y,x-i,2))
        if status != 3 or (x<w-1 and map[y][x+1] != "@"):
            for i in range(1, k + 1):
                if x+i >= w or map[y][x+i] == "@":
                    break
                else:
                    if gone[y][x+i] == 0:
                        gone[y][x+i] = 1
                        next.append((y,x+i,3))
    if next == deque():
        print(-1)
        exit()
    now = next

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from functools import lru_cache
h,w,k = map(int,input().split())
k = min(k,600)
sy,sx,gy,gx = map(int,input().split())
sy,sx,gy,gx = sy-1,sx-1,gy-1,gx-1
map = [str(input()) for i in range(h)]
gone = [[0] * w for i in range(h)]
now = deque()
now.append((sy,sx,-1))
gone[sy][sx] = 1
if map[gy][gx] == "@":
    print(-1)
    exit()
for ans in range(10 ** 6+1):
    next = deque()
    while now:
        y,x,status = now.popleft()
        if y == gy and x == gx:
            print(ans)
            exit()
        if status != 0 or (y>0 and map[y-1][x] != "@"):
            for i in range(1,k+1):
                if y-i < 0 or map[y-i][x] == "@":
                    break
                else:
                    if gone[y-i][x] == 0:
                        gone[y-i][x] = 1
                        next.append((y-i,x,0))
        if status != 1 or (y<h-1 and map[y+1][x] != "@"):
            for i in range(1,k+1):
                if y +i >= h or map[y+i][x] == "@":
                    break
                else:
                    if gone[y + i][x] == 0:
                        gone[y + i][x] = 1
                        next.append((y+i,x,1))
        if status != 2 or (x>0 and map[y][x-1] != "@"):
            for i in range(1,k+1):
                if x - i < 0 or map[y][x-i] == "@":
                    break
                else:
                    if gone[y][x-i] == 0:
                        gone[y][x-i] = 1
                        next.append((y,x-i,2))
        if status != 3 or (x<w-1 and map[y][x+1] != "@"):
            for i in range(1, k + 1):
                if x+i >= w or map[y][x+i] == "@":
                    break
                else:
                    if gone[y][x+i] == 0:
                        gone[y][x+i] = 1
                        next.append((y,x+i,3))
    if next == deque():
        print(-1)
        exit()
    now = next

Submission status: Time Limit Exceeded

Solution code:
def main():
  import sys
  input=sys.stdin.readline
  h,w,k=map(int,input().split())
  sx,sy,tx,ty=map(int,input().split())
  calc=lambda x,y:x*1000007+y
  b=[[-1]*(w+2)]
  for i in range(h):
    s=input()
    bb=[-1]
    for j in s:
      if j==".":bb.append(0)
      else:bb.append(-1)
    bb.append(-1)
    b.append(bb)
  b.append([-1]*(w+2))
  d=[]
  d.append((sx,sy))
  s=set()
  for ss in d:
    x,y=ss
    if calc(x,y)in s:
      s.discard(calc(x,y))
      continue
    if x==tx and y==ty:
      exit(print(b[x][y]))
    for i in range(1,k+1):
      if b[x-i][y]<=b[x][y] and b[x-i][y]!=0:break
      d.append((x-i,y))
      if b[x-i][y]!=0:
        s.add(calc(x-i,y))
      b[x-i][y]=b[x][y]+1
    for i in range(1,k+1):
      if b[x+i][y]<=b[x][y] and b[x+i][y]!=0:break
      d.append((x+i,y))
      if b[x+i][y]!=0:
        s.add(calc(x+i,y))
      b[x+i][y]=b[x][y]+1
    for j in range(1,k+1):
      if b[x][y-j]<=b[x][y] and b[x][y-j]!=0:break
      d.append((x,y-j))
      if b[x][y-j]!=0:
        s.add(calc(x,y-j))
      b[x][y-j]=b[x][y]+1
    for j in range(1,k+1):
      if b[x][y+j]<=b[x][y] and b[x][y+j]!=0:break
      d.append((x,y+j))
      if b[x][y+j]!=0:
        s.add(calc(x,y+j))
      b[x][y+j]=b[x][y]+1
  print(-1)
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]


H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
POND = [input().rstrip() for _ in range(H)]
vst = [[0] * W for _ in range(H)]
x1 -= 1; y1 -= 1
x2 -= 1; y2 -= 1

q = [(x1, y1)]
vst[x1][y1] = 1

for x0, y0 in q:
    for i in range(4):
        for d in range(1, K + 1):
            xx, yy = x0 + d * dx[i], y0 + d * dy[i]
            if 0 <= xx < H and 0 <= yy < W:
                if POND[xx][yy] == '@': break
                if POND[xx][yy] == '.' and vst[xx][yy] == 0:
                    vst[xx][yy] = vst[x0][y0] + 1
                    q.append((xx, yy))


if vst[x2][y2] == 0:
    print(-1)
else:
    print(vst[x2][y2] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
Dy = (-1,0,1,0)
Dx = (0,1,0,-1)

from collections import deque,defaultdict,Counter
def main():
    H,W,K = map(int,input().split())
    sy,sx,gy,gx = map(int,input().split())
    sy -= 1; sx -= 1; gy -= 1;gx -= 1
    pond = [list(input()) for _ in range(H)]
    
    q = deque([(sy,sx)])
    dist = [[-1]*W for _ in range(H)]
    dist[sy][sx] = 0
    while q:
        oy,ox = q.popleft()
        for dy,dx in zip(Dy,Dx):
            y,x = oy,ox
            for _ in range(K):
                y += dy
                x += dx
                if y < 0 or y >= H:
                    break
                if x < 0 or x >= W:
                    break
                if pond[y][x] == '@':
                    break
                if dist[y][x] >= 0:
                    continue
                dist[y][x] = dist[oy][ox] + 1
                q.append((y,x))
                if (y,x) == (gy,gx):
                    break
    print(dist[gy][gx] if dist[gy][gx] >= 0 else -1) 
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin, log, log10, gcd
from itertools import permutations, combinations, product, accumulate, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
#from fractions import gcd
from decimal import *
def debug(*args):
    if debugmode:
        print(*args)
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def FLOAT(): return float(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7
dx = [0, 1, 0, -1, 1, -1, -1, 1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
debugmode = True

h, w, k = MAP()
sx, sy, gx, gy = MAP()
sx -= 1
sy -= 1
gx -= 1
gy -= 1
c = [STR() for _ in range(h)]
arr = [[inf for _ in range(w)] for _ in range(h)]
for i in range(h):
    for j in range(w):
        arr[i][j] = (abs(gx - i) + k - 1) // k + (abs(gy - j) + k - 1) // k
marked = [[inf for _ in range(w)] for _ in range(h)]
marked[sx][sy] = 0
que = [[sx, sy, -1, 0, 0]]
while que:
    x, y, l_mov, cnt, num = que.pop()
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if ny < 0 or w <= ny or nx < 0 or h <= nx:
            continue
        if c[nx][ny] == '@':
            continue
        n_num = num
        n_cnt = cnt
        if l_mov == i and cnt < k:
            n_cnt += 1
        else:
            n_num += 1
            n_cnt = 1
        if marked[nx][ny] >= n_num:
            marked[nx][ny] = n_num
            if nx == gx and ny == gy:
                continue
            if n_num + arr[nx][ny] > marked[gx][gy]:
                continue
            que.append([nx, ny, i, n_cnt, n_num])
#for i in marked:
#    print(i)
ans = marked[gx][gy]
print(ans if ans != inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

h, w, k = map(int, input().split())
sx, sy, gx, gy = map(int, input().split())
sx -= 1
sy -= 1
gx -= 1
gy -= 1
c = [input() for _ in range(h)]
visited = [[False for _ in range(w)] for _ in range(h)]

def is_in_range(x, y):
    return 0 <= x < h and 0 <= y < w

def calc_cost(x, y):
    return 0 if gy == y and gx == x else (1 if gy == y or gx == x else 2)

pq = [(0, 0, (sx, sy))]
d = [(1, 0), (0, 1), (-1, 0), (0, -1)]
visited[sx][sy] = True
heapq.heapify(pq)

def search():
    while len(pq) != 0:
        _, cost, (cx, cy) = heapq.heappop(pq)
        # print(cost, (cx, cy))
        for dx, dy in d:
            for kk in range(1, k + 1):
                nx, ny = cx + dx * kk, cy + dy * kk
                if not is_in_range(nx, ny):
                    break
                if c[nx][ny] == '@':
                    break
                # print((nx, ny))
                if not visited[nx][ny]:
                    visited[nx][ny] = True
                    if c[nx][ny] == '.':
                        if ny == gy and nx == gx:
                            return cost + 1
                        heapq.heappush(pq, (calc_cost(nx, ny) + cost + 1, cost + 1, (nx, ny)))

    return -1

print(search())

Submission status: Time Limit Exceeded

Solution code:
def main():
  import sys
  input=sys.stdin.readline
  h,w,k=map(int,input().split())
  sx,sy,tx,ty=map(int,input().split())
  calc=lambda x,y:x*1000007+y
  b=[[-1]*(w+2)]
  for i in range(h):
    s=input()
    bb=[-1]
    for j in s:
      if j==".":bb.append(0)
      else:bb.append(-1)
    bb.append(-1)
    b.append(bb)
  b.append([-1]*(w+2))
  d=[]
  d.append(calc(sx,sy))
  s=set()
  for ss in d:
    x,y=divmod(ss,1000007)
    if calc(x,y)in s:
      s.discard(calc(x,y))
      continue
    if x==tx and y==ty:
      exit(print(b[x][y]))
    for i in range(1,k+1):
      if b[x-i][y]<=b[x][y] and b[x-i][y]!=0:break
      d.append(calc(x-i,y))
      if b[x-i][y]!=0:
        s.add(calc(x-i,y))
      b[x-i][y]=b[x][y]+1
    for i in range(1,k+1):
      if b[x+i][y]<=b[x][y] and b[x+i][y]!=0:break
      d.append(calc(x+i,y))
      if b[x+i][y]!=0:
        s.add(calc(x+i,y))
      b[x+i][y]=b[x][y]+1
    for j in range(1,k+1):
      if b[x][y-j]<=b[x][y] and b[x][y-j]!=0:break
      d.append(calc(x,y-j))
      if b[x][y-j]!=0:
        s.add(calc(x,y-j))
      b[x][y-j]=b[x][y]+1
    for j in range(1,k+1):
      if b[x][y+j]<=b[x][y] and b[x][y+j]!=0:break
      d.append(calc(x,y+j))
      if b[x][y+j]!=0:
        s.add(calc(x,y+j))
      b[x][y+j]=b[x][y]+1
  print(-1)
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
h,w,k = map(int, input().split())
sx,sy,gx,gy = map(int, input().split())
sx-=1
sy-=1
gx-=1
gy-=1

grid = ['' for _ in range(h)]

for i in range(h):
    grid[i] = input()
INF = 1001001001001001001  
costgrid = [[INF]*w for _ in range(h)]

import heapq

q = []
q.append((0,sx,sy))

dx = (0,1,0,-1)
dy = (1,0,-1,0)
ans=INF
while q:
    cost,x,y = heapq.heappop(q)
    for i in range(4):
        for j in range(1,k+1):
            nx = x+dx[i]*j
            ny = y+dy[i]*j
            if(not 0<=nx<h):
                break
            if(not 0<=ny<w):
                break
            if(grid[nx][ny]=='@'):
                break
            if(costgrid[nx][ny]!=INF):
                continue
            costgrid[nx][ny]=min(costgrid[nx][ny],cost+1)
            heapq.heappush(q,(cost+1,nx,ny))
            if nx==gx and ny==gy:
                ans=min(costgrid[nx][ny],ans)
                q=[]

if ans!=INF:
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
#####your code here#####
#G
import pprint
H,W,K=map(int,input().split())
import copy
x1,y1,x2,y2=map(int,input().split())
#raw=["#"]+["."]*(601)+["#"]
lastraw=["@"]*(W+2)
field=[["@"]*(W+2)]
for i in range(H):
  field.append(["@"]+list(input())+["@"])

field.append(lastraw)

#print(field)

goal_point=(y2,x2)

[sy,sx]=[y1,x1]
[gy,gx]=[y2,x2]

field[x1][y1]=0
queue=[[sy,sx]]
tests = ((-1,0),(0, 1),(1, 0),(0, -1))
moves=0

while True:
  if len(queue)==0:
    moves=-1
    break
  queue_next = []
  moves += 1
  #pprint.pprint(field)
  for y, x in queue:
    for ny, nx in tests:
      ty, tx = y + ny, x + nx
      if field[tx][ty] == '.' or field[tx][ty] ==moves:
        field[tx][ty] = moves
        queue_next.append((ty, tx))
        #print(ty,tx)
        for i in range(K-1):
          ty, tx = ty + ny, tx + nx
          if field[tx][ty] == '.' or field[tx][ty] ==moves:
            field[tx][ty] = moves
            queue_next.append((ty, tx))
            #print(ty,tx)
          else:
            break
  queue = queue_next
  if goal_point in queue:
    break
#pprint.pprint(field)
print(moves)

Submission status: Time Limit Exceeded

Solution code:
import queue
import sys
input = sys.stdin.readline
h,w,k = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx -= 1
sy -= 1
gx -= 1
gy -= 1
c = ["" for _ in range(h)]
for i in range(h):
  ci = str(input())
  c[i] = ci
d = [float("inf") for _ in range(w*h)]
q = queue.Queue()
q.put((sx,sy,0))
d[w*sx+sy] = 0
while not q.empty():
  nx,ny,p = q.get()
  for i,j in [(1,0),(-1,0),(0,1),(0,-1)]:
    ax = nx + i
    ay = ny + j
    kc = 1
    while  kc <= k and ax >=0 and ax < h and ay >=0 and ay < w and c[ax][ay]=="." and d[w*ax+ay] > p:
      if ax == gx and ay == gy:
        print(p+1)
        exit()
      if d[w*ax+ay] != p:
        d[w*ax+ay] = p+1
        q.put((ax,ay,p+1))
      kc += 1
      ax += i
      ay += j
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from functools import lru_cache
h,w,k = map(int,input().split())
k = min(k,10**3)
sy,sx,gy,gx = map(int,input().split())
sy,sx,gy,gx = sy-1,sx-1,gy-1,gx-1
map = [str(input()) for i in range(h)]
gone = [[0] * w for i in range(h)]
now = deque()
now.append((sy,sx,-1))
gone[sy][sx] = 1
if map[gy][gx] == "@":
    print(-1)
    exit()
for ans in range(10 ** 6+1):
    next = deque()
    while now:
        y,x,status = now.popleft()
        if y == gy and x == gx:
            print(ans)
            exit()
        if status != 0 or (y>0 and map[y-1][x] != "@"):
            for i in range(1,k+1):
                if y-i < 0 or map[y-i][x] == "@":
                    break
                else:
                    if gone[y-i][x] == 0:
                        gone[y-i][x] = 1
                        next.append((y-i,x,0))
        if status != 1 or (y<h-1 and map[y+1][x] != "@"):
            for i in range(1,k+1):
                if y +i >= h or map[y+i][x] == "@":
                    break
                else:
                    if gone[y + i][x] == 0:
                        gone[y + i][x] = 1
                        next.append((y+i,x,1))
        if status != 2 or (x>0 and map[y][x-1] != "@"):
            for i in range(1,k+1):
                if x - i < 0 or map[y][x-i] == "@":
                    break
                else:
                    if gone[y][x-i] == 0:
                        gone[y][x-i] = 1
                        next.append((y,x-i,2))
        if status != 3 or (x<w-1 and map[y][x+1] != "@"):
            for i in range(1, k + 1):
                if x+i >= w or map[y][x+i] == "@":
                    break
                else:
                    if gone[y][x+i] == 0:
                        gone[y][x+i] = 1
                        next.append((y,x+i,3))
    if next == deque():
        print(-1)
        exit()
    now = next

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h, w, k = map(int, input().split())
y1, x1, y2, x2 = map(int, input().split())
x1 -= 1
x2 -= 1
y1 -= 1
y2 -= 1

c = []
for _ in range(h):
    c.append(list(input()))
check = [[False for _ in range(w)] for _ in range(h)]
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

queue = deque()
queue.append([x1, y1])
queue.append(0)
while queue:
    pos = queue.popleft()
    ans = queue.popleft() + 1
    for dx, dy in directions:
        next_x = pos[0]
        next_y = pos[1]
        for _ in range(1, k + 1):
            next_x += dx
            next_y += dy
            if next_x == -1 or next_x == w or next_y == -1 or next_y == h:
                break
            if check[next_y][next_x]:
                continue
            if c[next_y][next_x] == "@":
                break
            check[next_y][next_x] = True
            if next_y == y2 and next_x == x2:
                print(ans)
                exit()
            queue.append([next_x, next_y])
            queue.append(ans)

print(-1)