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

Solution (Python):
from collections import deque
h, w, k = map(int, input().split())
y1, x1, y2, x2 = map(int, input().split())
c = []
for _ in range(h):
    c.append(input())
q = deque([(x1-1, y1-1)])
dxdy = [(-1,0), (0,-1), (0,1), (1,0)]
dist = [[1000000]*w for _ in range(h)]
dist[y1-1][x1-1] = 0
while q:
    x, y = q.popleft()
    for ddx, ddy in dxdy:
        for i in range(1, k+1):
            dx = ddx*i
            dy = ddy*i
            if not (0<=x+dx<w and 0<=y+dy<h):
                break
            if c[y+dy][x+dx]=='@' or dist[y+dy][x+dx]<=dist[y][x]:
                break
            if x+dx==x2-1 and y+dy==y2-1:
                print(dist[y][x]+1)
                exit(0)
            if dist[y+dy][x+dx]>dist[y][x]+1:
                dist[y+dy][x+dx] = dist[y][x]+1
                q.append((x+dx, y+dy))
print(-1)

Solution (Python):
from collections import deque
h, w, k = map(int, input().split())
y1, x1, y2, x2 = map(int, input().split())
c = []
for _ in range(h):
    c.append(input())
q = deque([(x1-1, y1-1)])
dxdy = [(-1,0), (0,-1), (0,1), (1,0)]
dist = [[1000000]*w for _ in range(h)]
dist[y1-1][x1-1] = 0
while q:
    x, y = q.popleft()
    for ddx, ddy in dxdy:
        for i in range(1, k+1):
            dx = ddx*i
            dy = ddy*i
            if not (0<=x+dx<w and 0<=y+dy<h):
                break
            if c[y+dy][x+dx]=='@' or dist[y+dy][x+dx]<=dist[y][x]:
                break
            if x+dx==x2-1 and y+dy==y2-1:
                print(dist[y][x]+1)
                exit(0)
            if dist[y+dy][x+dx]>dist[y][x]+1:
                dist[y+dy][x+dx] = dist[y][x]+1
                q.append((x+dx, y+dy))
print(-1)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline


def bfs(i1, j1) -> list:
    U, D, L, R = 0, 1, 2, 3
    INF = 10 ** 18
    dist = [[INF] * w for _ in range(h)]
    dist[i1][j1] = 0
    q = deque([(0, i1, j1)])
    while q:
        d, i, j = q.popleft()
        
        
        for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            for length in range(1, k + 1):
                nxt_i = i + di * length
                nxt_j = j + dj * length
                if not(0 <= nxt_i < h and 0 <= nxt_j < w):
                    break
                if c[nxt_i][nxt_j] == "@":
                    break
                if dist[i][j] + 1 > dist[nxt_i][nxt_j]:
                    break
                if dist[i][j] + 1 < dist[nxt_i][nxt_j]:
                    dist[nxt_i][nxt_j] = dist[i][j] + 1
                    q.append((dist[nxt_i][nxt_j], nxt_i, nxt_j))
    return dist


h, w, k = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
c = [input() for i in range(h)]


x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
dist = bfs(x1, y1)
ans = dist[x2][y2]

if ans == 10 ** 18:
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True 
BIG = 10**18
R = 10**9 + 7


def ddprint(x):
  if DBG:
    print(x)

h,w,k = inm()
x1,y1,x2,y2 = inm()
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
c = []
for i in range(h):
    c.append(ins())
d = [[-1]*w for i in range(h)]
q = deque([(x1,y1)])
d[x1][y1] = 0
dir = [(0,1),(0,-1),(1,0),(-1,0)]
while len(q)>0:
    x,y = q.popleft()
    dd = d[x][y]+1
    for dx,dy in dir:
        for i in range(1,k+1):
            xx = x+i*dx
            yy = y+i*dy
            if xx<0 or h<=xx or yy<0 or w<=yy or \
               (d[xx][yy]>=0 and d[xx][yy]<dd) or c[xx][yy]=='@':
                break
            if d[xx][yy] == dd:
                continue
            d[xx][yy] = dd
            q.append((xx,yy))
            if xx==x2 and yy==y2:
                print(dd)
                exit()
print(-1)

Solution (Python):
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
sh, sw, gh, gw = sh - 1, sw - 1, gh - 1, gw - 1
G = [list(input()) for _ in range(H)]
INF = 10 ** 9


D = [[INF] * W for _ in range(H)]
D[sh][sw] = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
que = deque([(sh, sw)])

while que:
    nh, nw = que.pop()
    for dh, dw in directions:
        for k in range(1, K + 1):
            nx_h, nx_w = nh + k * dh, nw + k * dw
            if not (0 <= nx_h < H and 0 <= nx_w < W):
                break

            if G[nx_h][nx_w] == '@':
                break

            if D[nx_h][nx_w] < D[nh][nw] + 1:
                break

            if D[nx_h][nx_w] > D[nh][nw] + 1:
                D[nx_h][nx_w] = D[nh][nw] + 1
                que.appendleft((nx_h, nx_w))

print(D[gh][gw] if D[gh][gw] != INF else -1)

Solution (Python):
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
sh, sw, gh, gw = sh - 1, sw - 1, gh - 1, gw - 1
G = [list(input()) for _ in range(H)]
INF = 10 ** 9


D = [[INF] * W for _ in range(H)]
D[sh][sw] = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
que = deque([(sh, sw)])

while que:
    nh, nw = que.pop()
    for dh, dw in directions:
        for k in range(1, K + 1):
            nx_h, nx_w = nh + k * dh, nw + k * dw
            if not (0 <= nx_h < H and 0 <= nx_w < W):
                break

            if G[nx_h][nx_w] == '@':
                break

            if D[nx_h][nx_w] <= D[nh][nw]:
                break

            if D[nx_h][nx_w] > D[nh][nw] + 1:
                D[nx_h][nx_w] = D[nh][nw] + 1
                que.appendleft((nx_h, nx_w))

print(D[gh][gw] if D[gh][gw] != INF else -1)

Solution (Python):
import queue
import sys
input = sys.stdin.readline

def calc_next_point(x, y, vec, dist):
    if vec == 0:
        return x-dist, y
    elif vec == 1:
        return x, y+dist
    elif vec == 2:
        return x+dist, y
    else:
        return x, y-dist

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    pond = [[[-1]*4 for j in range(w+2)] for i in range(h+2)]
    for i in range(1, h+1):
        s = input()
        for j in range(w):
            if s[j] == ".":
                for l in range(4):
                    pond[i][j+1][l] = float("inf")
    qs = [queue.Queue(), queue.Queue()]
    for i in range(4):
        pond[x1][y1][i] = 0
        qs[0].put([0, x1, y1, i])
    p = 0
    minans = float("inf")
    g = False
    while not qs[0].empty() or not qs[1].empty():
        while not qs[p].empty():
            cost, x, y, vec = qs[p].get()
            np = (p+1)%2
            if cost >= minans:
                g = True
                break
            if x == x2 and y == y2:
                if cost < minans:
                    minans = cost
                g = True
                break
            for i in range(1, k+1):
                nx, ny = calc_next_point(x, y, vec, i)
                if pond[nx][ny][vec] == -1:
                    break
                ncost = cost + 1
                if pond[nx][ny][vec] < ncost:
                    break
                if pond[nx][ny][vec] == ncost:
                    continue
                pond[nx][ny][vec] = ncost
                if nx == x2 and ny == y2:
                    if ncost < minans:
                        minans = ncost
                    g = True
                    break
                for j in range(4):
                    if i == k:
                        if j != (vec+2)%4:
                            if j == vec or pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
                    elif i == 1:
                        if j != vec:
                            if j == (vec+2)%4 or pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
                    else:
                        if j != vec and j != (vec+2)%4:
                            if pond[nx][ny][j] > ncost:
                                pond[nx][ny][j] = ncost
                                qs[np].put([ncost, nx, ny, j])
            if g:
                break
        if g:
            break
        p = (p+1)%2
    if min(pond[x2][y2]) == float("inf"):
        print(-1)
    else:
        print(min(pond[x2][y2]))

if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import deque
sys.setrecursionlimit(10**6)


def main(input, print):
    vx = [0, 1, 0, -1]
    vy = [-1, 0, 1, 0]

    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())
    table = [[] for _ in range(H)]
    for i in range(H):
        table[i] = list(input().strip())
    q = deque()
    q.append((x1-1, y1-1, 0))
    table[x1-1][y1-1] = 0
    while len(q) > 0:
        x, y, cnt = q.popleft()
        for i in range(4):
            for k in range(1, K+1):
                nx = x + vx[i] * k
                ny = y + vy[i] * k
                if nx < 0 or ny < 0 or nx >= H or ny >= W:
                    break
                if table[nx][ny] == '@':
                    break
                if table[nx][ny] != '.':
                    if table[nx][ny] < cnt + 1:
                        break
                    else:
                        continue
                table[nx][ny] = cnt+1
                q.append((nx, ny, cnt+1))
    if table[x2-1][y2-1] == '.':
        print(-1)
    else:
        print(table[x2-1][y2-1])


if __name__ == '__main__':
    main(sys.stdin.readline, print)

Solution (Python):
from collections import deque
H, W, K = map(int, input().split())
sx, sy, gx, gy = map(int, input().split())
sx -= 1
sy -= 1
gx -= 1
gy -= 1
grid = [input() for _ in range(H)]


def inside(r, c):
    return 0 <= r < H and 0 <= c < W and grid[r][c] != '@'


dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
INF = 10**9
dist = [[INF]*W for _ in range(H)]
que = deque()
que.append([sx, sy])
dist[sx][sy] = 0
while que:
    [x, y] = que.popleft()
    for k in range(4):
        for d in range(1, K+1):
            nx = x + d*dx[k]
            ny = y + d*dy[k]
            if not inside(nx, ny) or dist[nx][ny] <= dist[x][y]:
                break




            if dist[nx][ny] == INF:
                dist[nx][ny] = dist[x][y] + 1
                que.append([nx, ny])
if dist[gx][gy] == INF:
    print(-1)
else:
    print(dist[gx][gy])

Solution (Python):
import sys
input = sys.stdin.buffer.readline

H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
state = [list(input().rstrip()) for _ in range(H)]

q = [(x1-1, y1-1)]
checked = [[-1]*W for _ in range(H)]
checked[x1-1][y1-1] = 0
while q:
    qq = []
    for x, y in q:
        d = checked[x][y]
        dx = 1
        while x+dx < H and state[x+dx][y] == ord(".") and dx <= K:
            if checked[x+dx][y] == -1:
                checked[x+dx][y] = d + 1
                qq.append((x+dx, y))
            elif checked[x+dx][y] >= d + 1:
                checked[x+dx][y] = d + 1
            else:
                break
            dx += 1
        dx = -1
        while x+dx >= 0 and state[x+dx][y] == ord(".") and dx >= -K:
            if checked[x+dx][y] == -1:
                checked[x+dx][y] = d + 1
                qq.append((x+dx, y))
            elif checked[x+dx][y] >= d+1:
                checked[x+dx][y] = d + 1
            else:
                break
            dx -= 1
        dy = 1
        while y+dy < W and state[x][y+dy] == ord(".") and dy <= K:
            if checked[x][y+dy] == -1:
                checked[x][y+dy] = d + 1
                qq.append((x, y+dy))
            elif checked[x][y+dy] >= d+1:
                checked[x][y+dy] = d+1
            else:
                break
            dy += 1
        dy = -1
        while y+dy >= 0 and state[x][y+dy] == ord(".") and dy >= -K:
            if checked[x][y+dy] == -1:
                checked[x][y+dy] = d + 1
                qq.append((x, y+dy))
            elif checked[x][y+dy] >= d+1:
                checked[x][y+dy] = d+1
            else:
                break
            dy -= 1
    q = qq

print(checked[x2-1][y2-1])

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

INF = 10**18

H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split())
C = [input() for _ in range(H)]

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

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

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

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

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

Solution (Python):
from collections import deque

INF = 10**18

H, W, K = map(int, input().split())
x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split())
C = [input() for _ in range(H)]

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

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

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

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

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

Solution (Python):
from collections import deque
h,w,k = map(int,input().split())
a,b,c,d = map(int,input().split())
a -= 1
b -= 1
c -= 1
d -= 1
maze = [input() for _ in range(h)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
depth = [[float("inf") for _ in range(w)] for _ in range(h)]
dq = deque([(b,a)])
depth[a][b] = 0
while dq:
    x,y = dq.popleft()
    if x == d and y == c:
        break
    for i in range(4):
        nx,ny,K = x,y,k
        while K:
            K -= 1
            nx += dx[i]
            ny += dy[i]
            if 0<=nx<=w-1 and 0<=ny<=h-1 and maze[ny][nx] != "@" and depth[ny][nx] > depth[y][x]:
                if depth[ny][nx] == depth[y][x]+1:
                    continue
                depth[ny][nx] = depth[y][x] +1
                dq.append((nx,ny))
            else:
                break
print(depth[c][d] if depth[c][d] != float("inf") else -1)

Solution (Python):

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

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

Solution (Python):
from heapq import heappop, heappush 
from collections import deque
def dijkstra(xs, ys, xg, yg,h,w,k,field):
    
    inf = 1e18
    dist = [[inf]*w for _ in range(h)]
    dist[xs][ys] = 0
    que = deque([(0, xs, ys)])
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    while que:
        cost, x, y = que.popleft()
        if cost > dist[x][y]:
            continue
        for v in range(4):
            nx, ny = x, y
            for _ in range(k):
                nx += dx[v]
                ny += dy[v]
                if not field[nx][ny]:
                    break
                if dist[nx][ny]<=dist[x][y]:
                    break
                if dist[nx][ny] > dist[x][y]+1:
                    dist[nx][ny] = dist[x][y]+1
                    que.append((dist[nx][ny], nx, ny))

    if dist[xg][yg] == inf:
        print(-1)
    else:
        print(dist[xg][yg])

        

def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    h, w, k = map(int, input().split())
    xs, ys, xg, yg = map(int, input().split())
    field = [[False]*(w+2) for _ in range(h+2)]
    for i in range(h):
        
        s = [True if _ == '.' else False for _ in input()]
        field[i+1] = [False]+s+[False]
    h += 2
    w += 2
    dijkstra(xs, ys, xg, yg, h, w, k, field)

if __name__ == '__main__':
    main()

Solution (Python):
Dy = [0,1,0,-1]
Dx = [1,0,-1,0]
H, W, K = map(int, input().split())
y1,x1,y2,x2 = map(int, input().split())
C = ["@" + input() + "@" for _ in range(H)]
C = ["@"*(W+2)] + C + ["@"*(W+2)]
L = [[1]*(W+2) for _ in range(H+2)]
R = [[1]*(W+2) for _ in range(H+2)]
U = [[1]*(W+2) for _ in range(H+2)]
D = [[1]*(W+2) for _ in range(H+2)]
q = [(y1, x1)]
ans = 0
while q:
    q_new = []
    for y0, x0 in q:
        if (y0, x0) == (y2, x2):
            print(ans)
            exit()
        for dy, dx, Next in zip(Dy, Dx, [L, R, U, D]):
            y, x = y0, x0
            sum_next = 0
            Path = [(y, x)]
            while True:
                sum_next += Next[y][x]
                y = y0 + dy * sum_next
                x = x0 + dx * sum_next
                if sum_next > K:
                    break
                if C[y][x] == "@":
                    break
                Path.append((y, x))
                q_new.append((y, x))
            for path_y, path_x in Path:
                Next[path_y][path_x] = abs(path_y-y) + abs(path_x-x)
    q = q_new
    ans += 1

print(-1)

Solution (Python):
import sys
from collections import deque
def input(): return sys.stdin.readline().rstrip()

def main():
    def bfs():
        

        inf = 1e7

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

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

Solution (Python):
import sys
from collections import deque
def input(): return sys.stdin.readline().rstrip()

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

    inf = 1e7

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

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h, w, k = LI()
x1, y1, x2, y2 = LI()
c = [input() for _ in range(h)]

que = deque()
que.append((y1-1, x1-1))
dp = [[inf] * w for _ in range(h)]
dp[x1-1][y1-1] = 0
while que:
    x, y = que.popleft()
    for i in range(4):
        if i == 0:
            for ki in range(k):
                nx = x + (ki + 1)
                if 0 <= nx < w:
                    if c[y][nx] == '.':
                        if dp[y][nx] < dp[y][x] + 1:
                            break
                        elif dp[y][nx] == dp[y][x] + 1:
                            continue
                        dp[y][nx] = dp[y][x] + 1
                        que.append((nx, y))
                    else:
                        break
                else:
                    break
        elif i == 1:
            for ki in range(k):
                ny = y + (ki + 1)
                if 0 <= ny < h:
                    if c[ny][x] == '.':
                        if dp[ny][x] < dp[y][x] + 1:
                            break
                        elif dp[ny][x] == dp[y][x] + 1:
                            continue
                        dp[ny][x] = dp[y][x] + 1
                        que.append((x, ny))
                    else:
                        break
                else:
                    break
        elif i == 2:
            for ki in range(k):
                nx = x - (ki + 1)
                if 0 <= nx < w:
                    if c[y][nx] == '.':
                        if dp[y][nx] < dp[y][x] + 1:
                            break
                        elif dp[y][nx] == dp[y][x] + 1:
                            continue 
                        dp[y][nx] = dp[y][x] + 1
                        que.append((nx, y))
                    else:
                        break
                else:
                    break
        else:
            for ki in range(k):
                ny = y - (ki + 1)
                if 0 <= ny < h:
                    if c[ny][x] == '.':
                        if dp[ny][x] < dp[y][x] + 1:
                            break
                        elif dp[ny][x] == dp[y][x] + 1:
                            continue
                        dp[ny][x] = dp[y][x] + 1
                        que.append((x, ny))
                    else:
                        break
                else:
                    break
ans = dp[x2-1][y2-1]
if ans == inf:
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque
h,w,k = map(int,input().split())
a,b,c,d = map(int,input().split())
a -= 1
b -= 1
c -= 1
d -= 1
maze = [input() for _ in range(h)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
depth = [[float("inf") for _ in range(w)] for _ in range(h)]
dq = deque([(b,a)])
depth[a][b] = 0
while dq:
    x,y = dq.popleft()
    if x == d and y == c:
        break
    for i in range(4):
        nx,ny,K = x,y,k
        while K:
            K -= 1
            nx += dx[i]
            ny += dy[i]
            if 0<=nx<=w-1 and 0<=ny<=h-1 and maze[ny][nx] != "@" and depth[ny][nx] > depth[y][x]:
                if depth[ny][nx] == depth[y][x]+1:
                    continue
                depth[ny][nx] = depth[y][x] +1
                dq.append((nx,ny))
            else:
                break
print(depth[c][d] if depth[c][d] != float("inf") else -1)

Solution (Python):
from collections import deque
h,w,k = map(int,input().split())
a,b,c,d = map(int,input().split())
a -= 1
b -= 1
c -= 1
d -= 1
maze = [input() for _ in range(h)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
depth = [[float("inf") for _ in range(w)] for _ in range(h)]
dq = deque([(b,a)])
depth[a][b] = 0
while dq:
    x,y = dq.popleft()
    if x == d and y == c:
        break
    for i in range(4):
        nx,ny,K = x,y,k
        while K:
            K -= 1
            nx += dx[i]
            ny += dy[i]
            if 0<=nx<=w-1 and 0<=ny<=h-1 and maze[ny][nx] != "@" and depth[ny][nx] > depth[y][x]:
                if depth[ny][nx] == depth[y][x]+1:
                    continue
                depth[ny][nx] = depth[y][x] +1
                dq.append((nx,ny))
            else:
                break
print(depth[c][d] if depth[c][d] != float("inf") else -1)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random,resource

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    h,w,k = LI()
    y1,x1,y2,x2 = LI_()
    ca = [S() for _ in range(h)]

    aa = [[-1 if c == '@' else inf for c in s] for s in ca]
    aa[y1][x1] = 0
    q = [(y1,x1)]
    v = collections.defaultdict(bool)
    t = 0
    while q:
        t += 1
        nq = []
        for y,x in q:
            for dy, dx in dd:
                for i in range(1, k+1):
                    ty = y + dy * i
                    tx = x + dx * i
                    if ty < 0 or ty >= h or tx < 0 or tx >= w or aa[ty][tx] < t:
                        break

                    if aa[ty][tx] == t:
                        continue

                    aa[ty][tx] = t
                    nq.append((ty,tx))

        q = nq

    if aa[y2][x2] == inf:
        return -1

    return aa[y2][x2]


print(main())

Solution (Python):

from collections import deque
h,w,k = list(map(int, input().split()))
x1,y1,x2,y2 = list(map(int, input().split()))
x1,y1,x2,y2 = x1-1,y1-1,x2-1,y2-1
dp = [[-1]*w for _ in range(h)]

que = deque()
c = [input() for _ in range(h)]

dp[x1][y1] = 0

que.append((x1,y1))
dx = [1,0,-1,0]
dy = [0,1,0,-1]
while que:
  
  
  p = que.popleft()
  if (p[0] == x2) & (p[1] == y2):exit(print(dp[x2][y2]))
  for i in range(4):
    for j in range(1,k+1):
      nx = p[0] + dx[i]*j
      ny = p[1] + dy[i]*j
      if not ((0 <= nx < h) & (0 <= ny < w)):break
      if c[nx][ny] == '@':break
      if 0 <= dp[nx][ny] <= dp[p[0]][p[1]]:break
      if dp[nx][ny] == -1:
        
        que.append((nx,ny))
      dp[nx][ny] = dp[p[0]][p[1]] + 1

print(-1)

Solution (Python):

from collections import deque
h,w,k = list(map(int, input().split()))
x1,y1,x2,y2 = list(map(int, input().split()))
x1,y1,x2,y2 = x1-1,y1-1,x2-1,y2-1
dp = [[-1]*w for _ in range(h)]

que = deque()
c = [input() for _ in range(h)]

dp[x1][y1] = 0

que.append((x1,y1))
dx = [1,0,-1,0]
dy = [0,1,0,-1]
while que:
  
  
  x,y = que.popleft()
  if (x == x2) & (y == y2):exit(print(dp[x2][y2]))
  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) & (0 <= ny < w)):break
      if c[nx][ny] == '@':break
      if 0 <= dp[nx][ny] <= dp[x][y]:break
      if dp[nx][ny] == -1:
        
        que.append((nx,ny))
      dp[nx][ny] = dp[x][y] + 1

print(-1)

Solution (Python):

from collections import deque
h,w,k = list(map(int, input().split()))
x1,y1,x2,y2 = list(map(int, input().split()))
x1,y1,x2,y2 = x1-1,y1-1,x2-1,y2-1
dp = [[-1]*w for _ in range(h)]

que = deque()
c = [input() for _ in range(h)]

dp[x1][y1] = 0

que.append((x1,y1))
dx = [1,0,-1,0]
dy = [0,1,0,-1]
while que:
  x,y=que.popleft()
  if x==x2 and y==y2:
    exit(print(dp[x][y]))
  for dx,dy in [[1,0],[-1,0],[0,-1],[0,1]]:
    for i in range(1,k+1):
      xx=x+dx*i
      yy=y+dy*i
      if not(0<=xx<h and 0<=yy<w) or c[xx][yy]=="@":break
      if 0<=dp[xx][yy]<=dp[x][y]:break
      if dp[xx][yy]==-1:que.append((xx,yy))
      dp[xx][yy]=dp[x][y]+1
print(-1)