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, 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 *
import heapq
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 = [[0, sx, sy, -1, 0]]
heapq.heapify(que)
while que:
    num, x, y, l_mov, cnt = heapq.heappop(que)
    if num >= marked[gx][gy]:
        break
    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([n_num, nx, ny, i, n_cnt])
#for i in marked:
#    print(i)
ans = marked[gx][gy]
print(ans if ans != inf else -1)
#print(-1)

Submission status: Time Limit Exceeded

Solution code:
from random import randint
if randint(1,2)==1:
  from collections import deque
  import sys
  input=sys.stdin.readline
  calc=lambda x,y:x*1000007+y
  def main():
    h,w,k=map(int,input().split())
    sx,sy,tx,ty=map(int,input().split())
    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=deque()
    d.append(calc(sx,sy))
    s=set()
    while d:
      x,y=divmod(d.popleft(),1000007)
      if calc(x,y)in s:
        s.discard((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((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((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((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((x,y+j))
        b[x][y+j]=b[x][y]+1
    print(-1)
  if __name__ == "__main__":
    main()
else:
  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))
    from collections import deque
    d=deque()
    d.append((sx,sy))
    s=set()
    while d:
      x,y=d.popleft()
      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:
from collections import deque
from functools import lru_cache

directions = [ (-1,0),(1,0),(0,-1),(0,1) ]
    
def no_ans(i1,j1, i2,j2, board,H,W):
    q = deque()
    visited = set()
    visited.add((i2,j2))
    q.append( (i2, j2) )
    while q :
        i, j = q.popleft()
        if (i, j) == (i1,j1) :
            return False

        for di, dj in directions:
            ni = di+i
            nj = dj+j
            if ni < 0 or ni >= H or nj < 0 or nj >= W or board[ni][nj] == '@' :
                continue
            if (ni, nj) in visited :
                continue
            visited.add((ni, nj))
            q.append( (ni, nj) )
    return True

@lru_cache
def solve():
    H, W, K = map(int, input().split(" "))
    i1, j1, i2, j2 = map(lambda x: int(x)-1, input().split(" "))
    board = []
    for _ in range(H):
        board.append( list(input()))
    visited = [ [-1]*W for _ in range(H) ]

    q = deque()
    visited[i1][j1] = 0
    q.append( (i1, j1, 0) )

    if no_ans(i1,j1, i2,j2, board,H,W) :
        return -1

    while q:
        i, j, v  = q.popleft()
        if (i,j)==(i2,j2) :
            return visited[i][j]
        if v > visited[i][j] :
            continue

        for di, dj in directions:
            for k in range(1, K+1):
                ni = di*k+i
                nj = dj*k+j
                if ni < 0 or ni >= H or nj < 0 or nj >= W or board[ni][nj] == '@' :
                    break 
                if visited[ni][nj] > visited[i][j] + 1 :
                    break 

                if visited[ni][nj] == -1 :
                    visited[ni][nj] = visited[i][j] + 1
                    q.append( (ni, nj, visited[ni][nj]) )

    return visited[i2][j2]

print(solve())

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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)

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 = 1001001001  
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:
import os
import heapq

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

H, W, K = list(map(int, sys.stdin.buffer.readline().split()))
sx, sy, gx, gy = list(map(int, sys.stdin.buffer.readline().split()))
C = [sys.stdin.buffer.readline().decode().rstrip() for _ in range(H)]

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

u_hist = [[(INF, INF, INF)] * W for _ in range(H)]
d_hist = [[(INF, INF, INF)] * W for _ in range(H)]
l_hist = [[(INF, INF, INF)] * W for _ in range(H)]
r_hist = [[(INF, INF, INF)] * W for _ in range(H)]
u_hist[sx][sy] = (0, 0, 0)
d_hist[sx][sy] = (0, 0, 0)
l_hist[sx][sy] = (0, 0, 0)
r_hist[sx][sy] = (0, 0, 0)
hist = (u_hist, d_hist, l_hist, r_hist)
D = ((0, 1), (1, 0), (0, -1), (-1, 0))

ans = INF
heap = [(0, 0, 0, sx, sy, 0), (0, 0, 0, sx, sy, 1), (0, 0, 0, sx, sy, 2), (0, 0, 0, sx, sy, 3)]
while heap:
    p, s, cnt, x, y, d = heapq.heappop(heap)
    # p = s + cnt / K
    if (p, s, cnt) > hist[d][x][y]:
        continue
    for i in range(4):
        if (p-2, s, cnt) > hist[i][x][y]:
            continue
    if x == gx and y == gy:
        ans = min(ans, s + (cnt + K - 1) // K)
    for i in range(4):
        nd = (d + i) % 4
        dx, dy = D[nd]
        nx = x + dx
        ny = y + dy
        if not (0 <= nx < H and 0 <= ny < W):
            continue
        if C[nx][ny] == '@':
            continue
        if nd == d:
            np = s + (cnt + 1) / K
            if hist[nd][nx][ny] < (np, s, cnt + 1):
                continue
            hist[nd][nx][ny] = (np, s, cnt + 1)
            heapq.heappush(heap, (np, s, cnt + 1, nx, ny, nd))
        else:
            ns = s + (cnt + K - 1) // K
            ncnt = 1
            np = ns + 1 / K
            if hist[nd][nx][ny] < (np, ns, ncnt):
                continue
            hist[nd][nx][ny] = (np, ns, ncnt)
            heapq.heappush(heap, (np, ns, ncnt, nx, ny, nd))

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

Submission status: Time Limit Exceeded

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

H,W,K=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
MAP=[list(input().strip()) for i in range(H)]

for i in range(H):
    for j in range(W):
        if MAP[i][j]==".":
            MAP[i][j]=1<<30
        else:
            MAP[i][j]=-1

Q=deque()
b=10**6+1
Q.append(x1-1+(y1-1)*b)
MAP[x1-1][y1-1]=0

while Q:
    P=Q.pop()
    y=P//b
    x=P%b

    for i in range(1,K+1):
        if 0<=x+i<H and 0<=y<W and (MAP[x+i][y]==1<<30 or MAP[x+i][y]>MAP[x][y]):
            MAP[x+i][y]=MAP[x][y]+1
            Q.appendleft(x+i+y*b)
        else:
            break

    for i in range(1,K+1):
        if 0<=x-i<H and 0<=y<W and (MAP[x-i][y]==1<<30 or MAP[x-i][y]>MAP[x][y]):
            MAP[x-i][y]=MAP[x][y]+1
            Q.appendleft(x-i+y*b)
        else:
            break

    for i in range(1,K+1):
        if 0<=x<H and 0<=y+i<W and (MAP[x][y+i]==1<<30 or MAP[x][y+i]>MAP[x][y]):
            MAP[x][y+i]=MAP[x][y]+1
            Q.appendleft(x+(y+i)*b)
        else:
            break

    for i in range(1,K+1):
        if 0<=x<H and 0<=y-i<W and (MAP[x][y-i]==1<<30 or MAP[x][y-i]>MAP[x][y]):
            MAP[x][y-i]=MAP[x][y]+1
            Q.appendleft(x+(y-i)*b)
        else:
            break
if MAP[x2-1][y2-1]==1<<30:
    print(-1)
else:
    print(MAP[x2-1][y2-1])

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() for _ in range(h)]
x1,y1 = y1-1,x1-1
x2,y2 = y2-1,x2-1

q = deque([(x1,y1,0)])
dist = [[-1]*w for _ in range(h)]
over = {}
over["right"] = [[0]*w for _ in range(h)]
over["left"]  = [[0]*w for _ in range(h)]
over["up"]    = [[0]*w for _ in range(h)]
over["down"]  = [[0]*w for _ in range(h)]
while q:
    x,y,d = q.popleft()
    dist[y][x] = d
    if y == y2 and x == x2: break
    for dx,dy,direction in [(-1,0,"left"),(1,0,"right"),(0,-1,"down"),(0,1,"up")]:
        count = over[direction][y][x]+1      
        newx = x+dx*count
        newy = y+dy*count
        while 0<=newx<w and 0<=newy<h and count<=k and c[newy][newx]==".":
                        
            if dist[newy][newx] == -1:
                q.append((newx,newy,d+1))
            newx += dx
            newy += dy
            count += 1

        over_x = x+dx*(count-1)
        over_y = y+dy*(count-1)
        over_count = 0
        while count>over[direction][y][x]:
            over[direction][over_y][over_y] = 0
            over_x -= dx
            over_y -= dy
            count -= 1
            over_count += 1
            
            
        
print(dist[y2][x2])

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,"D")] = 0
  seen[(x1,y1,"R")] = 0
  seen[(x1,y1,"U")] = 0
  seen[(x1,y1,"L")] = 0
  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,dire) in seen and seen[(i,j,dire)] <= cost:
      continue
    if i == x2 and j == y2:
      return cost
    seen[(i,j,dire)] = 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:
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))
  from collections import deque
  d=deque()
  d.append((sx,sy))
  s=set()
  while d:
    x,y=d.popleft()
    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:
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)])
                    if nx == gx and ny == gy:
                        print(d[gx][gy])
                        return
    print(d[gx][gy])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
c = "@" * (W+2)
for _ in range(H):
	c += "@" + input() + "@"
c += "@" * (W+2)
#c = ["@" * (W+2)] + ["@" + input() + "@" for _ in range(H)] + ["@" * (W+2)]
INF = 10**6+5
dist = [INF for _ in range((W+2) * (H+2))]
dist[sh*(W+2)+sw] = 0
q = deque()
q.append(sh*(W+2)+sw)
DI = [1, 0, -1, 0]
DJ = [0, 1, 0, -1]
while q:
	l = q.popleft()
	i, j = l//(W+2), l%(W+2)
	for di, dj in zip(DI, DJ):
		for k in range(1, K+1):
			ii, jj = i+di*k, j+dj*k
			if c[ii*(W+2)+jj] == "." and dist[ii*(W+2)+jj] > dist[i*(W+2)+j]:
				dist[ii*(W+2)+jj] = dist[i*(W+2)+j] + 1
				if ii == gh and jj == gw:
					print(dist[ii*(W+2)+jj])
					sys.exit()
				q.append(ii*(W+2) + jj)
			else:
				break
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,555)
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:
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*10**6+sy)
d[w*sx+sy] = 0
while not q.empty():
  pp = q.get()
  nx = pp//10**6
  ny = pp%10**6
  p = d[w*nx+ny]
  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*10**6+ay)
      kc += 1
      ax += i
      ay += j
print(-1)

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())
  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
    t=x*1000000+y
    if t in s:
      s.discard(t)
      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(t-1000000*i)
      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(t+1000000*i)
      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(t-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(t+j)
      b[x][y+j]=b[x][y]+1
  print(-1)
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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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)
            heapq.heappush(q, (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:
import os
import heapq

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

H, W, K = list(map(int, sys.stdin.buffer.readline().split()))
sx, sy, gx, gy = list(map(int, sys.stdin.buffer.readline().split()))
C = [sys.stdin.buffer.readline().decode().rstrip() for _ in range(H)]

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

u_hist = [[(INF, INF, INF)] * W for _ in range(H)]
d_hist = [[(INF, INF, INF)] * W for _ in range(H)]
l_hist = [[(INF, INF, INF)] * W for _ in range(H)]
r_hist = [[(INF, INF, INF)] * W for _ in range(H)]
u_hist[sx][sy] = (0, 0, 0)
d_hist[sx][sy] = (0, 0, 0)
l_hist[sx][sy] = (0, 0, 0)
r_hist[sx][sy] = (0, 0, 0)
hist = (u_hist, d_hist, l_hist, r_hist)
D = ((0, 1), (1, 0), (0, -1), (-1, 0))

ans = INF
heap = [(0, 0, 0, sx, sy, 0), (0, 0, 0, sx, sy, 1), (0, 0, 0, sx, sy, 2), (0, 0, 0, sx, sy, 3)]
while heap:
    p, s, cnt, x, y, d = heapq.heappop(heap)
    # p = s + cnt / K
    if (p, s, cnt) > hist[d][x][y]:
        continue
    if x == gx and y == gy:
        ans = min(ans, s + (cnt + K - 1) // K)
    for i in range(4):
        nd = (d + i) % 4
        dx, dy = D[nd]
        nx = x + dx
        ny = y + dy
        if not (0 <= nx < H and 0 <= ny < W):
            continue
        if C[nx][ny] == '@':
            continue
        if nd == d:
            np = s + (cnt + 1) / K
            if hist[nd][nx][ny] < (np, s, cnt + 1):
                continue
            hist[nd][nx][ny] = (np, s, cnt + 1)
            heapq.heappush(heap, (np, s, cnt + 1, nx, ny, nd))
        else:
            ns = s + (cnt + K - 1) // K
            ncnt = 1
            np = ns + 1 / K
            if hist[nd][nx][ny] < (np, ns, ncnt):
                continue
            hist[nd][nx][ny] = (np, ns, ncnt)
            heapq.heappush(heap, (np, ns, ncnt, nx, ny, nd))

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