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:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

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

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print(cost // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        print(a)
                    else:
                        while True:
                            pass
                        print(a)
                exit()

    print(-1)

main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

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

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print((cost+1) // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        print(a)
                    else:
                        print(a)
                exit()

    print(-1)

main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

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

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print(cost // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        print(a)
                    else:
                        print(a)
                exit()

    print(-1)

main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

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

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print(cost // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        print(a)
                    else:
                        print(a-1)
                exit()

    print(-1)

main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

import heapq

def main():
    h, w, k = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    # surround the square with '@'
    c = [['@'] * (w+2)]
    for _ in range(h):
        i = list('@' + input() + '@')
        c.append(i)
    c.append(['@'] * (w+2))

    # Dijkstra
    seen = [[0] * (w+2) for _ in range(h+2)]
    # todo.append((cost, x, y, direction))
    # direction:: None: -1, north: 0, east: 1, south: 2, west: 3
    todo = [(k, x1, y1, -1)]
    heapq.heapify(todo)

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

    while len(todo) > 0:
        cost, xi, yi, direction = heapq.heappop(todo)

        if seen[xi][yi] != 0:
            continue

        seen[xi][yi] = cost

        for j in range(4):
            xj, yj= xi + dx[j], yi + dy[j]

            if c[xj][yj] == '@':
                continue

            if seen[xj][yj] == 0:
                if j == direction:
                    heapq.heappush(todo, (cost+1, xj, yj, j))
                else:
                    a, b = divmod(cost, k)
                    if b == 0:
                        heapq.heappush(todo, (cost+1, xj, yj, j))
                    else:
                        heapq.heappush(todo, (k*(a+1) + 1, xj, yj, j))
            
            if xj == x2 and yj == y2:
                if j == direction:
                    print(cost // k)
                else:
                    a, b = divmod(cost, k)
                    if b != 0:
                        print(a)
                    else:
                        print(a+1)
                exit()

    print(-1)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

grid = [None]*h
for i in range(h):
  grid[i] = input()

not_yet = deque([])
already = [[False]*w for _ in range(h)]
dist = [[0]*w for _ in range(h)]
judgement_h = [[False]*w for _ in range(h)]
judgement_w = [[False]*w for _ in range(h)]

not_yet.append((x1-1, y1-1))
already[x1-1][y1-1] = True

while not_yet:
  key = not_yet.popleft()
  k1, k2 = key[0], key[1]
  judgement_h[k1][k2] = True
  judgement_w[k1][k2] = True
  
  for i in range(k1-1, max([-1, k1-k-1]), -1):
    if judgement_h[i][k2]:
      break
    elif grid[i][k2] == "@":
      break
    elif not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
  for i in range(k1+1, min([h, k1+k+1])):
    if judgement_h[i][k2]:
      break
    elif grid[i][k2] == "@":
      break
    elif not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
  for i in range(k2-1, max([-1, k2-k-1]), -1):
    if judgement_w[k1][i] == True:
      break
    elif grid[k1][i] == "@":
      break
    elif not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
  for i in range(k2+1, min([w, k2+k+1])):
    if judgement_w[k1][i] == True:
      break
    elif grid[k1][i] == "@":
      break
    elif not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
      
if dist[x2-1][y2-1] == 0:
  print(-1)
else:
  print(dist[x2-1][y2-1])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

grid = [None]*h
for i in range(h):
  grid[i] = input()

not_yet = deque([])
already = [[False]*w for _ in range(h)]
dist = [[0]*w for _ in range(h)]
judgement_h = [[False]*w for _ in range(h)]
judgement_w = [[False]*w for _ in range(h)]

not_yet.append((x1-1, y1-1))
already[x1-1][y1-1] = True

while not_yet:
  key = not_yet.popleft()
  k1, k2 = key[0], key[1]
  judgement_h[k1][k2] = True
  judgement_w[k1][k2] = True
  
  for i in range(k1-1, max([-1, k1-k-1]), -1):
    if judgement_h[i][k2]:
      break
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
    elif grid[i][k2] == "@":
      break
  for i in range(k1+1, min([h, k1+k+1])):
    if judgement_h[i][k2]:
      break
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
    elif grid[i][k2] == "@":
      break
  for i in range(k2-1, max([-1, k2-k-1]), -1):
    if judgement_w[k1][i] == True:
      break
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
    elif grid[k1][i] == "@":
      break
  for i in range(k2+1, min([w, k2+k+1])):
    if judgement_w[k1][i] == True:
      break
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
    elif grid[k1][i] == "@":
      break
      
if dist[x2-1][y2-1] == 0:
  print(-1)
else:
  print(dist[x2-1][y2-1])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

grid = [None]*h
for i in range(h):
  grid[i] = input()

not_yet = deque([])
already = [[False]*w for _ in range(h)]
dist = [[0]*w for _ in range(h)]
judgement_h = [[False]*w for _ in range(h)]
judgement_w = [[False]*w for _ in range(h)]

not_yet.append((x1-1, y1-1))
already[x1-1][y1-1] = True

while not_yet:
  key = not_yet.popleft()
  k1, k2 = key[0], key[1]
  
  for i in range(k1-1, max([-1, k1-k-1]), -1):
    if judgement_h[i][k2]:
      break
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
    elif grid[i][k2] == "@":
      break
  for i in range(k1+1, min([h, k1+k+1])):
    if judgement_h[i][k2]:
      break
    if not already[i][k2] and grid[i][k2] == ".":
      dist[i][k2] = dist[k1][k2] + 1
      already[i][k2] = True
      not_yet.append((i, k2))
      judgement_h[i][k2] = True
    elif grid[i][k2] == "@":
      break
  for i in range(k2-1, max([-1, k2-k-1]), -1):
    if judgement_w[k1][i] == True:
      break
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
    elif grid[k1][i] == "@":
      break
  for i in range(k2+1, min([w, k2+k+1])):
    if judgement_w[k1][i] == True:
      break
    if not already[k1][i] and grid[k1][i] == ".":
      dist[k1][i] = dist[k1][k2] + 1
      already[k1][i] = True
      not_yet.append((k1, i))
      judgement_w[k1][i] = True
    elif grid[k1][i] == "@":
      break
      
if dist[x2-1][y2-1] == 0:
  print(-1)
else:
  print(dist[x2-1][y2-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
import math
import sys

N_MAX = 200000 + 5
sys.setrecursionlimit(N_MAX)

H, W, K = map(int, sys.stdin.readline().split())
x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
INF = 10**6 * K

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

for h in range(H):
    s = sys.stdin.readline()
    for w in range(W):
        if s[w] == "@":
            dp[h][w] = -1

### BFS ###

# ステップ方向
D = [0, 1, 2, 3]  # direction
Y = [1, 0, -1, 0]
X = [0, 1, 0, -1]

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

    while q:
        # print(q)
        x0, y0 = q.popleft()

        for x, y in zip(X, Y):

            for i in range(1,K+1):

                # print(y0,y,x0,x,d, (y0+y,x0+x,d), end=" : ")
                dp_c = dp[x0][y0]  # 現在のdp値
                n_x, n_y = x0+x*i, y0+y*i

                # print(dp_c, (n_x,n_y), end=" : ")

                if (n_x)<0 or (n_x)>=H or (n_y)<0 or (n_y)>=W:
                    # print("out of range")
                    break

                if dp[n_x][n_y] == -1:
                    # print("@")
                    break

                if dp[n_x][n_y] != INF:
                    break

                dp[n_x][n_y] = dp_c + 1
                q.append((n_x, n_y))


# スタート地点を 0 にする
dp[x1-1][y1-1] = 0

# print(x1-1,y1-1)
# print(dp)

bfs(x1-1,y1-1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2 - 1][y2 - 1] == INF:
    print(-1)
else:
    print(dp[x2 - 1][y2 - 1])

Submission status: Wrong Answer

Solution code:
from collections import deque
import math
import sys

N_MAX = 200000 + 5
sys.setrecursionlimit(N_MAX)

H, W, K = map(int, sys.stdin.readline().split())
x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
INF = 10**6 * K

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

for h in range(H):
    s = sys.stdin.readline()
    for w in range(W):
        if s[w] == "@":
            dp[h][w] = -1

### BFS ###

# ステップ方向
D = [0, 1, 2, 3]  # direction
Y = [1, 0, -1, 0]
X = [0, 1, 0, -1]

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

    while q:
        # print(q)
        x0, y0 = q.popleft()

        for x, y in zip(X, Y):

            for i in range(1,K+1):

                # print(y0,y,x0,x,d, (y0+y,x0+x,d), end=" : ")
                dp_c = dp[x0][y0]  # 現在のdp値
                n_x, n_y = x0+x*i, y0+y*i

                # print(dp_c, (n_x,n_y), end=" : ")

                if (n_x)<0 or (n_x)>=H or (n_y)<0 or (n_y)>=W:
                    # print("out of range")
                    break

                if dp[n_x][n_y] == -1:
                    # print("@")
                    break

                if dp[n_x][n_y] <= dp_c + 1:
                    break

                dp[n_x][n_y] = dp_c + 1
                q.append((n_x, n_y))


# スタート地点を 0 にする
dp[x1-1][y1-1] = 0

# print(x1-1,y1-1)
# print(dp)

bfs(x1-1,y1-1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2 - 1][y2 - 1] == INF:
    print(-1)
else:
    print(dp[x2 - 1][y2 - 1])

Submission status: Wrong Answer

Solution code:
# fast input
from heapq import heappop, heappush
import sys
input = sys.stdin.buffer.readline
INF = 10 ** 10
# INF = float("inf")

try:
    profile
except:
    def profile(f): return f

DEBUG = True
if DEBUG:
    def dp(*x):  # debugprint
        print(*x)
else:
    def dp(*x): pass


@profile
def main(H, W, K, x1, y1, x2, y2, mapdata):
    # H, W, K = map(int, input().split())
    # x1, y1, x2, y2 = map(int, input().split())
    # mapdata = sys.stdin.buffer.read().splitlines()
    # print(data)
    start = (x1, y1)
    goal = x2 * W + y2

    #distances = {}
    distances = [(INF, 0)] * (H * W * 5)
    # defaultdict(lambda: (INF, 0))
    # distances[(start, 0)] = (0, 0)
    key = (x1 * W + y1) * 5 + 0
    distances[key] = (0, 0)

    shortest_path = {}
    shortest_path[key] = 0

    queue = [((0, 0), key)]
    DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while queue:
        (d, frac), pos_dir = heappop(queue)
        pos, direction = divmod(pos_dir, 5)
        x, y = divmod(pos, W)
        # dp("(frm, direction)", (frm, direction))
        # dp("distances[(frm, direction)]", distances[(frm, direction)])
        dist = distances[pos_dir]
        if dist < (d, frac):
            # already know shorter path
            continue
        if pos == goal:
            break

        # same direction
        # dp("direction", direction)
        dx, dy = DIRS[direction]
        nx = x + dx
        ny = y + dy
        # dp("nx, ny", nx, ny)
        if mapdata[nx * W + ny]:
            if frac == 0:
                newd = d + 1
                newfrac = -K + 1
            else:
                newd = d
                newfrac = frac + 1
            newdist = (newd, newfrac)
            to = (nx * W + ny) * 5 + direction

            if distances[to] > newdist:
                # found shorter path
                distances[to] = newdist
                heappush(queue, (newdist, to))
                shortest_path[to] = pos_dir

        if direction < 2:
            # facing X axis
            dir = 2
            nx = x
            ny = y + 1
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

            dir = 3
            nx = x
            ny = y - 1
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir
        else:
            # facing Y axis
            dir = 0
            nx = x + 1
            ny = y
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

            dir = 1
            nx = x - 1
            ny = y
            if mapdata[nx * W + ny]:
                newdist = (d + 1, -K + 1)

                to = (nx * W + ny) * 5 + dir
                if distances[to] > newdist:
                    # found shorter path
                    distances[to] = newdist
                    heappush(queue, (newdist, to))
                    shortest_path[to] = pos_dir

        # dp("distances", distances)

    result = min(distances[goal * 5:goal * 5+4])
    if result[0] == INF:
        # unreachable
        return -1
    else:
        return result[0]


# print(sys.argv)
if sys.argv[-1] == 'ONLINE_JUDGE':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', 'i8(i8,i8,i8,i8,i8,i8,i8,b1[:])')(main)
    # b1[:],i8,i8,i8,i8,i8
    cc.compile()
    exit()
else:
    H, W, K = map(int, input().split())
    x1, y1, x2, y2 = map(int, input().split())

    from my_module import main
    import numpy as np
    C = np.zeros((H + 2, W + 2), np.bool_)
    data = np.frombuffer(
        sys.stdin.buffer.read(),
        'S1')
    # print(data)
    data = data.reshape(H, -1)
    # print(data)
    data = data[:, : W] == b'.'
    # print(data)
    C[1: -1, 1: -1] = data
    C = C.ravel()
    H += 2
    W += 2

    print(main(H, W, K, x1, y1, x2, y2, C))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, sysread().split())
    x1,y1, x2, y2 = map(int, sysread().split())
    MAP = [['@'] * (W+2)]
    for i in range(H):
        tmp = deque(list(str(sysread()))[:-1])
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(tmp)
    MAP.append(['@'] * (W+2))
    print(MAP)

    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+2)] for _ in range(H+2)]

    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > best_time:
            continue
        if x==x2 and y==y2:
            best_time = time
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] >= time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] >= time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))


    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
from collections import deque
import math
import sys

N_MAX = 200000 + 5
sys.setrecursionlimit(N_MAX)

H, W, K = map(int, sys.stdin.readline().split())
x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
INF = 10**6 * K

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

for h in range(H):
    s = sys.stdin.readline()
    for w in range(W):
        if s[w] == "@":
            dp[h][w] = -1

### BFS ###

# ステップ方向
D = [0, 1, 2, 3]  # direction
Y = [1, 0, -1, 0]
X = [0, 1, 0, -1]

def bfs(x1, y1):
    
    q = deque()
    q.append((x1, y1, 0))
    q.append((x1, y1, 1))
    q.append((x1, y1, 2))
    q.append((x1, y1, 3))

    while q:
        # print(q)
        x0, y0, d0 = q.popleft()

        for x, y, d in zip(X, Y, D):

            # print(y0,y,x0,x,d, (y0+y,x0+x,d), end=" : ")
            dp_c = dp[x0][y0]  # 現在のdp値
            n_x, n_y = x0+x, y0+y

            # print(dp_c, (n_x,y0+y,d), end=" : ")

            if (n_x)<0 or (n_x)>=H or (n_y)<0 or (n_y)>=W:
                # print("out of range")
                continue

            if dp[n_x][n_y] == -1:
                # print("@")
                continue

            # 後ろを向いている場合
            if d % 4 == (d0+2)%4:
                # print("back")
                continue

            # 同方向を向いている場合
            if d % 4 == d0 % 4:
                if dp[n_x][n_y] <= dp_c + 1:
                    # print("not update / same d")
                    continue
                else:
                    dp[n_x][n_y] = dp_c + 1  # 更新

            # 90°方向を変えた場合
            elif d%4 == (d0+1)%4 or d%4 == (d0+3) % 4:
                if dp[n_x][n_y] <= K * math.ceil(dp_c/K) + 1:
                    # print("not update / 90")
                    continue
                else:
                    dp[n_x][n_y] = K * math.ceil(dp_c/K) + 1

            q.append((n_x, n_y, d))


# スタート地点を 0 にする
dp[x1-1][y1-1] = 0

# print(x1-1,y1-1)
# print(dp)

bfs(x1-1,y1-1)

# print(dp)
# print(x2-1,y2-1)

if dp[x2 - 1][y2 - 1] == INF:
    print(-1)
else:
    print(math.ceil(dp[x2 - 1][y2 - 1]/K))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
# from copy import deepcopy
from collections import deque
#import numba

def run():
    H, W, K = map(int, input().split())
    x1,y1, x2, y2 = map(int, input().split())
    MAP = [['@'] * (W+2)]
    for i in range(H):
        tmp = deque(list(input()))
        tmp.appendleft('@')
        tmp.append('@')
        MAP.append(tmp)
    MAP.append(['@'] * (W+2))


    INF = float('inf')
    queue = deque([])
    queue.append((1, (x1, y1, 0, 0)))# time, x, y, direction, seq
    queue.append((1, (x1, y1, 1, 0)))
    queue.append((1, (x1, y1, 2, 0)))
    queue.append((1, (x1, y1, 3, 0)))

    checked = [[[INF] * 4 for i in range(W+1)] for _ in range(H+1)]

    checked[x1][y1][0] = 1
    checked[x1][y1][1] = 1
    checked[x1][y1][2] = 1
    checked[x1][y1][3] = 1

    command = [(0, 1,0), (1,0,1), (2,-1,0), (3,0,-1)]
    best_time = INF
    while queue:
        time, (x, y, direction, seq) = queue.popleft()
        if time > min(checked[x2][y2]):
            continue
        for k, i, j in command:
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x][n_y][k] > time and seq < K:
                    checked[n_x][n_y][k] = time
                    queue.append((time, (n_x, n_y, k, seq + 1)))
                elif (k != direction or seq == K) and checked[n_x][n_y][k] > time + 1:
                    checked[n_x][n_y][k] = time + 1
                    queue.append((time + 1, (n_x, n_y, k, 1)))

    best_time = min(checked[x2][y2])
    if best_time == INF:
        print(-1)

    else:
        print(best_time)




if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque

h,w,k= map(int, input().split())
sx,sy,gx,gy= map(int, input().split())
maze= [list(input()) for i in range(h)]


# 迷路　BFS
def clear_maze(sx, sy, gx, gy):

    INF=-10**9
    distance = [[INF for i in range(w)] for j in range(h)]
    #    distance = [[None]*field_x_length]*field_y_length
    def bfs():
        # きた点と方向を格納
        d=deque()
        d.append((sx, sy))
        distance[sx][sy] =0

        while len(d):
            x, y = d.popleft()

            for i in range(0, 4):
                for j in range(1,k+1):
                    nx, ny = x + [j, 0, -j, 0][i], y + [0, j, 0, -j][i]
                    if 0 <= nx < h and 0 <= ny < w:
                        if maze[nx][ny] != '@' and distance[nx][ny] == INF:
                            d.append((nx, ny))
                            distance[nx][ny] = distance[x][y] + 1

                        else:
                            break
                    else:
                        break

        return distance[gx][gy]

    return bfs()

ans=clear_maze(sx-1,sy-1,gx-1,gy-1)

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