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: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return map(int, input().split())
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#solve
def solve():
    mxy = [(0, 1), (1, 0), (-1, 0), (0, -1)]
    h, w, K = LI()
    y1, x1, y2, x2 = LI_()
    c = SR(h)
    q = deque()
    q.append((x1, y1, 0, 0))
    q.append((x1, y1, 1, 0))
    q.append((x1, y1, 2, 0))
    q.append((x1, y1, 3, 0))
    field = [None] * h
    for i in range(h):
        field[i] = [inf] * w
    field[y1][x1] = 0
    while q:
        x, y, d, k = q.popleft()
        mx, my = mxy[d]
        mx += x
        my += y
        if 0 <= my < h and 0 <= mx < w:
            if c[my][mx] == "@": continue
            s = field[y][x] + (k == 0)
            k += 1
            if k > K:
                s += 1
                k = 0
                if field[my][mx] > s:
                    field[my][mx] = s
                    q.append((mx, my, 0, k))
                    q.append((mx, my, 0, k))
                    q.append((mx, my, 0, k))
                    q.append((mx, my, 0, k))
            else:
                if field[my][mx] > s:
                    field[my][mx] = s
                    for i in range(4):
                        if i == d:
                            q.appendleft((mx, my, d, k))
                        else:
                            q.append((mx, my, i, 0))
    print(field[y2][x2] if field[y2][x2] != inf else -1)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
it = lambda: list(map(int, input().strip().split()))
INF = float('inf')


def solve():
    M, N, K = it()
    x1, y1, x2, y2 = it()
    x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1
    grid = [list(input().strip()) for _ in range(M)]

    ans = INF
    pq = [(0, 0, x1, y1)]
    while pq:
        c, d, x, y = heappop(pq)
        if x == x2 and y == y2:
            ans = min(ans, c)
            continue
        if grid[x][y] == '@':
            continue
        if c > ans:
            break
        grid[x][y] = '@'
        for x0, y0, d0 in ((x - 1, y, 1), (x + 1, y, 2), (x, y - 1, 3), (x, y + 1, 4)):
            if 0 <= x0 < M and 0 <= y0 < N and grid[x0][y0] != '@':
                c0 = (c + 1) if d in (0, d0) else ((c - 1) // K + 1) * K + 1
                heappush(pq, (c0, d0, x0, y0))
    return -1 if ans == INF else (ans - 1) // K + 1

if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
it = lambda: list(map(int, input().strip().split()))
INF = float('inf')


def solve():
    M, N, K = it()
    x1, y1, x2, y2 = it()
    x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1
    grid = [list(input().strip()) for _ in range(M)]

    pq = [(0, 0, x1, y1)]
    while pq:
        c, d, x, y = heappop(pq)
        if x == x2 and y == y2:
            return (c - 1) // K + 1 
        if grid[x][y] == '@':
            continue
        grid[x][y] = '@'
        for x0, y0, d0 in ((x - 1, y, 1), (x + 1, y, 2), (x, y - 1, 3), (x, y + 1, 4)):
            if 0 <= x0 < M and 0 <= y0 < N and grid[x0][y0] != '@':
                c0 = (c + 1) if d in (0, d0) else ((c - 1) // K + 1) * K + 1
                heappush(pq, (c0, d0, x0, y0))
    return -1

if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
it = lambda: list(map(int, input().strip().split()))
INF = float('inf')


def solve():
    M, N, K = it()
    x1, y1, x2, y2 = it()
    x1, y1, x2, y2 = x1 - 1, y1 - 1, x2 - 1, y2 - 1
    grid = [list(input().strip()) for _ in range(M)]
    cost = [[INF] * N for _ in range(M)]
    cost[x1][y1] = 0

    pq = [(0, 0, x1, y1)]
    while pq:
        c, d, x, y = heappop(pq)
        if x == x2 and y == y2:
            return (c - 1) // K + 1 
        if grid[x][y] == '@':
            continue
        grid[x][y] = '@'
        for x0, y0, d0 in ((x - 1, y, 1), (x + 1, y, 2), (x, y - 1, 3), (x, y + 1, 4)):
            if 0 <= x0 < M and 0 <= y0 < N and grid[x0][y0] != '@':
                c0 = (c + 1) if d in (0, d0) else ((c - 1) // K + 1) * K + 1
                if c0 <= cost[x0][y0]:
                    cost[x0][y0] = c0
                    heappush(pq, (c0, d0, x0, y0))
    return -1

if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

Solution code:
from collections import*
z,v,a=input,range,print
h,w,k=map(int,z().split());r,s,t,u=map(lambda x:int(x)-1,z().split());b=[z()for _ in v(h)];l=[[0]*w for _ in v(h)];l[r][s]=0;d=deque([(r,s)])
while d:
  x,y=d.popleft();j=l[x][y]
  if(x==t)&(y==u):exit(a(j))
  for e,f in[[1,0],[-1,0],[0,-1],[0,1]]:
    for i in v(1,k+1):
      p,q=x+e*i,y+f*i
      if not((0<=p<h)&(0<=q<w))or b[p][q]=="@" or 1<=l[p][q]<=j:break
      if l[p][q]:d+=[(p,q)];l[p][q]=j+1
a(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

field = []
field.append("@"*(w+2))
for _ in range(h):
    line = "@" + input() + "@"
    field.append(line)
field.append("@"*(w+2))


def fixed_positions(t, count):
    for _ in range(count):
        yield t


def kick(direction, y, x, height, width):
    if direction == "up":
        paths = zip(range(y, -1 ,-1), fixed_positions(x, y))
    elif direction == "down":
        paths = zip(range(y, height), fixed_positions(x, height-y))
    elif direction == "left":
        paths = zip(fixed_positions(y, x), range(x, -1, -1))
    else:
        paths = zip(fixed_positions(y, width-x), range(x, width))
    
    return paths


todo = deque([(sy, sx, 2)])
directions = ["up", "down", "left", "right"]
seen = [[False]*(w+2) for _ in range(h+2)]
seen[sy][sx] = 1

while todo:
    y, x, dist = todo.popleft()

    for direction in directions:
        for ny, nx in kick(direction, y, x, h+2, w+2):
            if field[ny][nx] == "@":
                break
            
            if not seen[ny][nx]:
                seen[ny][nx] = dist+1
                todo.append((ny, nx, dist+1))
                continue
                
            elif 1 <= seen[ny][nx] <= dist+1:
                continue
            
            break

            



ans = seen[gy][gx]
if ans == 0:
    ans = -1

print(ans-1)
for line in seen:
    print(line)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

field = []
field.append("@"*(w+2))
for _ in range(h):
    line = "@" + input() + "@"
    field.append(line)
field.append("@"*(w+2))


def fixed_positions(t, count):
    for _ in range(count):
        yield t


def kick(direction, y, x, height, width):
    if direction == "up":
        paths = zip(range(y, -1 ,-1), fixed_positions(x, y))
    elif direction == "down":
        paths = zip(range(y, height), fixed_positions(x, height-y))
    elif direction == "left":
        paths = zip(fixed_positions(y, x), range(x, -1, -1))
    else:
        paths = zip(fixed_positions(y, width-x), range(x, width))
    
    return paths


todo = deque([(sy, sx, 2)])
directions = ["up", "down", "left", "right"]
seen = [[False]*(w+2) for _ in range(h+2)]
seen[sy][sx] = 1

while todo:
    y, x, dist = todo.popleft()

    for direction in directions:
        for ny, nx in kick(direction, y, x, h+2, w+2):
            if not seen[ny][nx]:
                seen[ny][nx] = dist+1
                todo.append((ny, nx, dist+1))
                
            elif 1 <= seen[ny][nx] == dist+1:
                continue

            
            if field[ny][nx] == "@":
                break
            



ans = seen[gy][gx]
if ans == 0:
    ans = -1

print(ans-1)
for line in seen:
    print(line)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

field = []
field.append("@"*(w+2))
for _ in range(h):
    line = "@" + input() + "@"
    field.append(line)
field.append("@"*(w+2))


def fixed_positions(t, count):
    for _ in range(count):
        yield t


def kick(direction, y, x, height, width):
    if direction == "up":
        paths = zip(range(y, -1 ,-1), fixed_positions(x, y))
    elif direction == "down":
        paths = zip(range(y, height), fixed_positions(x, height-y))
    elif direction == "left":
        paths = zip(fixed_positions(y, x), range(x, -1, -1))
    else:
        paths = zip(fixed_positions(y, width-x), range(x, width))
    
    return paths


todo = deque([(sy, sx, 1)])
directions = ["up", "down", "left", "right"]
seen = [[False]*(w+2) for _ in range(h+2)]
seen[sy][sx] = 1

while todo:
    y, x, dist = todo.popleft()

    for direction in directions:
        for ny, nx in kick(direction, y, x, h+2, w+2):
            if seen[ny][nx] == dist+1:
                continue
            
            if seen[ny][nx]:
                break
            
            if field[ny][nx] == "@":
                break
            
            seen[ny][nx] = dist+1
            todo.append((ny, nx, dist+1))


ans = seen[gy][gx]
if ans == 0:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

field = []
field.append("@"*(w+2))
for _ in range(h):
    line = "@" + input() + "@"
    field.append(line)
field.append("@"*(w+2))


def fixed_positions(t, count):
    for _ in range(count):
        yield t


def kick(direction, y, x, height, width):
    if direction == "up":
        paths = zip(range(y, -1 ,-1), fixed_positions(x, y))
    elif direction == "down":
        paths = zip(range(y, height), fixed_positions(x, height-y))
    elif direction == "left":
        paths = zip(fixed_positions(y, x), range(x, -1, -1))
    else:
        paths = zip(fixed_positions(y, width-x), range(x, width))
    
    return paths


todo = deque([(sy, sx, 1)])
directions = ["up", "down", "left", "right"]
seen = [[False]*(w+2) for _ in range(h+2)]
seen[sy][sx] = 1

while todo:
    y, x, dist = todo.popleft()

    for direction in directions:
        for ny, nx in kick(direction, y, x, h+2, w+2):
            if seen[ny][nx] <= dist+2:
                break
            
            if seen[ny][nx]:
                continue
            
            if field[ny][nx] == "@":
                break
            
            seen[ny][nx] = dist+1
            todo.append((ny, nx, dist+1))


ans = seen[gy][gx]
if ans == 0:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

field = []
field.append("@"*(w+2))
for _ in range(h):
    line = "@" + input() + "@"
    field.append(line)
field.append("@"*(w+2))


def fixed_positions(t, count):
    for _ in range(count):
        yield t


def kick(direction, y, x, height, width):
    if direction == "up":
        paths = zip(range(y, -1 ,-1), fixed_positions(x, y))
    elif direction == "down":
        paths = zip(range(y, height), fixed_positions(x, height-y))
    elif direction == "left":
        paths = zip(fixed_positions(y, x), range(x, -1, -1))
    else:
        paths = zip(fixed_positions(y, width-x), range(x, width))
    
    return paths


todo = deque([(sy, sx, 1)])
directions = ["up", "down", "left", "right"]
seen = [[False]*(w+2) for _ in range(h+2)]
seen[sy][sx] = 1

while todo:
    y, x, dist = todo.popleft()

    for direction in directions:
        for ny, nx in kick(direction, y, x, h+2, w+2):
            if seen[ny][nx]:
                continue
            if field[ny][nx] == "@":
                break
            
            seen[ny][nx] = dist+1
            todo.append((ny, nx, dist+1))


ans = seen[gy][gx]
if ans == 0:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
z,v,a=input,range,print
h,w,k=map(int,z().split())
r,s,t,u=map(lambda x:int(x)-1,z().split())
b=[z()for _ in v(h)]
l=[[-1]*w for _ in v(h)]
l[r][s]=0
from collections import*
d=deque([(r,s)])
while d:
  x,y=d.popleft()
  if(x==t)&(y==u):exit(a(l[x][y]))
  for e,f in[[1,0],[-1,0],[0,-1],[0,1]]:
    for i in v(1,k+1):
      p,q=x+e*i,y+f*i
      if not((0<=p<h)&(0<=q<w))or b[p][q]=="@" or 0<=l[p][q]:break
      if l[p][q]<0:d+=[(p,q)];l[p][q]=l[x][y]+1
a(-1)

Submission status: Wrong Answer

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    h,w,k = map(int,ipt().split())
    x1,y1,x2,y2 = map(int,ipt().split())
    x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1
    ms = [input()+"@" for _ in range(h)]
    ms.append("@"*(w+1))
    hq = []
    al = [[10**18]*w for _ in range(h)]
    al[x1][y1] = 0
    dr = [(0,1),(1,0),(0,-1),(-1,0)]
    hpq.heappush(hq,(0,x1,y1))
    while hq:
        c,x,y = hpq.heappop(hq)
        cn = c+1
        if x == x2 and y == y2:
            print(c)
            exit()
        for dx,dy in dr:
            xx = x
            yy = y
            for i in range(k):
                xx += dx
                yy += dy
                if ms[xx][yy] == "." and al[xx][yy] > cn:
                    al[xx][yy] = cn
                    hpq.heappush(hq,(cn,xx,yy))
                else:
                    break
    print(-1)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    h,w,k = map(int,ipt().split())
    x1,y1,x2,y2 = map(int,ipt().split())
    x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1
    ms = [input()+"@" for _ in range(h)]
    ms.append("@"*(w+1))
    hq = []
    al = [[10**18]*w for _ in range(h)]
    al[x1][y1] = 0
    dr = [(0,1),(1,0),(0,-1),(-1,0)]
    hpq.heappush(hq,(0,x1,y1))
    while hq:
        c,x,y = hpq.heappop(hq)
        cn = c+1
        if x == x2 and y == y2:
            print(c)
            exit()
        for dx,dy in dr:
            xx = x
            yy = y
            for i in range(1,k+1):
                xx += dx
                yy += dy
                if ms[xx][yy] == "@" or al[xx][yy] <= cn:
                    break
                else:
                    al[xx][yy] = cn
                    hpq.heappush(hq,(cn,xx,yy))
    print(-1)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    h,w,k = map(int,ipt().split())
    x1,y1,x2,y2 = map(int,ipt().split())
    ltl = 10**(-9)
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1
    ms = [input()+"@" for _ in range(h)]
    ms.append("@"*(w+1))
    hq = []
    al = [[[10**18]*4 for _ in range(w)] for _ in range(h)]
    al[x1][y1][0] = 0
    al[x1][y1][1] = 0
    al[x1][y1][2] = 0
    al[x1][y1][3] = 0
    stp = 1/k+ltl
    dct = {0:(0,1),1:(1,0),2:(0,-1),3:(-1,0)}
    c90 = (1,-1)

    for i in range(4):
        hpq.heappush(hq,(0,x1,y1,i))
    while hq:
        c,x,y,d = hpq.heappop(hq)
        if x == x2 and y == y2:
            print(math.ceil(c))
            exit()
        dx,dy = dct[d]
        if ms[x+dx][y+dy] == "." and al[x+dx][y+dy][d] > c+stp:
            al[x+dx][y+dy][d] = c+stp
            hpq.heappush(hq,(c+stp,x+dx,y+dy,d))
        for i in c90:
            if al[x][y][(d+i)%4] > math.ceil(c):
                al[x][y][(d+i)%4] = math.ceil(c)
                hpq.heappush(hq,(math.ceil(c),x,y,(d+i)%4))
    print(-1)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    h,w,k = map(int,ipt().split())
    x1,y1,x2,y2 = map(int,ipt().split())
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1
    ms = [input()+"@" for _ in range(h)]
    ms.append("@"*(w+1))
    hq = []
    al = [[[10**18]*4 for _ in range(w)] for _ in range(h)]
    al[x1][y1][0] = 0
    al[x1][y1][1] = 0
    al[x1][y1][2] = 0
    al[x1][y1][3] = 0
    stp = 1/k
    dct = {0:(0,1),1:(1,0),2:(0,-1),3:(-1,0)}
    c90 = (1,-1)

    for i in range(4):
        hpq.heappush(hq,(0,x1,y1,i))
    while hq:
        c,x,y,d = hpq.heappop(hq)
        if x == x2 and y == y2:
            print(math.ceil(c))
            exit()
        dx,dy = dct[d]
        if ms[x+dx][y+dy] == "." and al[x+dx][y+dy][d] > c+stp:
            al[x+dx][y+dy][d] = c+stp
            hpq.heappush(hq,(c+stp,x+dx,y+dy,d))
        for i in c90:
            if al[x][y][(d+i)%4] > math.ceil(c):
                al[x][y][(d+i)%4] = math.ceil(c)
                hpq.heappush(hq,(math.ceil(c),x,y,(d+i)%4))
    print(-1)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def dijkstra():
    dist = [[[10**18]*4 for _ in range(W)] for _ in range(H)]
    pq = []
    
    for i in range(4):
        dist[x1-1][y1-1][i] = 0
        heappush(pq, (0, (x1-1, y1-1, i)))
    
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    
    while pq:
        d, (x, y, di) = heappop(pq)
        
        if dist[x][y][di]<d:
            continue
        
        for i in range(4):
            if dist[x][y][i]>(d+K-1)//K*K:
                dist[x][y][i] = (d+K-1)//K*K
                heappush(pq, (dist[x][y][i], (x, y, i)))
        
        nx = x+dx[di]
        ny = y+dy[di]
        
        if 0<=nx<H and 0<=ny<W and c[nx][ny]!='@':
            if dist[nx][ny][di]>d+1:
                dist[nx][ny][di] = d+1
                heappush(pq, (dist[nx][ny][di], (nx, ny, di)))
        
    return (min(dist[x2-1][y2-1])+K-1)//K

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

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

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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

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

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


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

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

        M[x1][y1] = d

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

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

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

                k += 1


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

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


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

Submission status: Wrong Answer

Solution code:
from collections import deque
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 = deque()
    que.append((x,y))
    d[x][y] = 0
    while que:
        (qx,qy) = que.popleft()
        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] == '@' or (d[nx][ny] != -1 and d[nx][ny] <= d[qx][qy]+1):
                    break
                if d[nx][ny] == -1 or d[nx][ny] > d[qx][qy]+1:
                    d[nx][ny] = d[qx][qy] + 1
                    que.append((nx,ny))
    print(d[gx][gy])
 
 
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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] == '@' or (d[nx][ny] != -1 and d[nx][ny] <= d[qx][qy]+1):
                    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: Wrong Answer

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] == '@' or (d[nx][ny] != -1 and d[nx][ny] <= d[qx][qy]+1):
                    break
                if d[nx][ny] == -1 or d[nx][ny] > d[qx][qy]+1:
                    d[nx][ny] = d[qx][qy] + 1
                    heappush(que,[abs(nx-gx)+abs(ny-gy),(nx,ny)])
                    if nx == gx and ny == gy:
                        print(d[gx][gy])
                        return
    print(d[gx][gy])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
from heapq import heapify, heappop, heappush

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W, K = lr()
X1, Y1, X2, Y2 = lr()
X1 -= 1; Y1 -= 1; X2 -= 1; Y2 -= 1
C = [sr() for _ in range(H)]
graph = [[] for _ in range((H*W)*4)]  # 0-indexed
for i in range(H):
    for j in range(W):
        pos = (W*i + j)*4
        left = False; right = False
        if C[i][j] == '@':
            continue
        if j == 0: left = True
        if j == W-1: right = True
        for con, dir in [(0, -4*W), (1, 4), (2, 4*W), (3, -4)]:
            # 0を上、1を右
            if left and con == 3: continue
            if right and con == 1: continue
            if 0 <= pos + con + dir < H*W*4:
                graph[pos + con].append(((pos+con+dir), 1 / K))
        for con in range(4):
            graph[pos+con].append(((pos+(con+1)%4), K+1))
            graph[pos+con].append(((pos+(con-1)%4), K+1))

INF = 10 ** 10

def dijkstra(start):
    dist = [INF] * H * W * 4
    que = [(0, start)]
    dist[start] = 0
    while que:
        d, prev = heappop(que)
        if dist[prev] < d:
            continue
        for next, dis in graph[prev]:
            if dis == K+1:
                d1 = -(-d//1)
            else:
                d1 = d + dis
            if dist[next] > d1:
                dist[next] = d1
                heappush(que, (d1, next))
    return dist

start = (W*X1+Y1)*4
dist = dijkstra(start)
goal = (W*X2 + Y2)*4
answer = min(dist[goal:goal+4])
answer = int(-(-answer//1))
print(answer if answer != INF else -1)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
h,w,k=map(int,input().split())
calc=lambda x,y,d:(x*w+y)*4+d
si,sj,ti,tj=map(int,input().split())
si-=1
sj-=1
ti-=1
tj-=1
b=[input()for _ in range(h)]
from heapq import heappop,heappush
edge=[[]for _ in range(h*w*4)]
for i in range(h):
  for j in range(1,w):
    if b[i][j-1]==b[i][j]==".":
      edge[calc(i,j-1,0)].append((calc(i,j,0),1))
      edge[calc(i,j,2)].append((calc(i,j-1,2),1))
for j in range(w):
  for i in range(1,h):
    if b[i-1][j]==b[i][j]==".":
      edge[calc(i-1,j,3)].append((calc(i,j,3),1))
      edge[calc(i,j,1)].append((calc(i-1,j,1),1))
for i in range(h):
  for j in range(w):
    edge[calc(i,j,0)].append((calc(i,j,1),0))
    edge[calc(i,j,1)].append((calc(i,j,0),0))
    edge[calc(i,j,0)].append((calc(i,j,3),0))
    edge[calc(i,j,3)].append((calc(i,j,0),0))
    edge[calc(i,j,2)].append((calc(i,j,1),0))
    edge[calc(i,j,1)].append((calc(i,j,0),0))
    edge[calc(i,j,2)].append((calc(i,j,3),0))
    edge[calc(i,j,3)].append((calc(i,j,2),0))
def dijkstra(s,n,edge):
  inf=10**20
  ans=[inf]*n
  ans[s]=0
  root=[-1]*n
  h=[[0,s]]
  while h:
    c,v=heappop(h)
    if ans[v]<c:continue
    for u,t in edge[v]:
      if t==0:m=int(0--c//1)
      else:m=c+1/k
      if m<ans[u]:
        ans[u]=m
        root[u]=v
        heappush(h,[m,u])
  return ans
ans=dijkstra(calc(si,sj,0),h*w*4,edge)
anss=min(int(0--ans[calc(ti,tj,l)]//1)for l in range(4))
if anss==10**20:print(-1)
else:print(anss)