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:
# 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 > best_time:
            continue
        elif 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:
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 = []
        e = []
        d.append((sx, sy))
        distance[sx][sy] =0

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

            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:
                            e.append((nx, ny))
                            distance[nx][ny] = distance[x][y] + 1

                        else:
                            break
                    else:
                        break
            d=e
        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)

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 > 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:
# 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 > 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:
                    if seq == K:
                        checked[n_x][n_y][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x][n_y][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif 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:
# 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))
    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+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 > 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:
                    if seq == K:
                        checked[n_x][n_y][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x][n_y][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif 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:
# 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):
        MAP.append('@' + input() + '@')
    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 > 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:
                    if seq == K:
                        checked[n_x][n_y][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x][n_y][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif 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:
# 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):
        MAP.append('@' + input() + '@')
    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 = [(1,0), (0,1), (-1,0), (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 enumerate(command):
            n_x = x+i
            n_y = y+j
            if MAP[n_x][n_y] == '.':
                if k == direction and checked[n_x-1][n_y-1][k] > time:
                    if seq == K:
                        checked[n_x-1][n_y-1][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x - 1][n_y - 1][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif checked[n_x-1][n_y-1][k] > time + 1:
                    checked[n_x-1][n_y-1][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:
# 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 = []
    for i in range(H):
        MAP.append(input())

    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)] for _ in range(H)]

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

    command = [(1,0), (0,1), (-1,0), (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 and best_time > time:
            best_time = time
        for k, (i,j) in enumerate(command):
            n_x = x+i
            n_y = y+j
            if 1 <= n_x <= H and 1 <= n_y <= W and MAP[n_x-1][n_y-1] == '.':
                if k == direction and checked[n_x-1][n_y-1][k] > time:
                    if seq == K:
                        checked[n_x-1][n_y-1][k] = time+1
                        queue.append((time+1, (n_x, n_y, k, 1)))
                    else:
                        checked[n_x - 1][n_y - 1][k] = time
                        queue.append((time, (n_x, n_y, k, seq+1)))
                elif checked[n_x-1][n_y-1][k] > time + 1:
                    checked[n_x-1][n_y-1][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:
# 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 = []
    for i in range(H):
        MAP.append(input())

    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)] for _ in range(H)]

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

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




if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
from heapq import heappush,heappop

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

# 迷路　ダイクストラ
def clear_maze(sx, sy, gx, gy, k):
    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 = []
        heappush(d,(0,sx, sy, k - 1, -1))
        distance[sx][sy] = 0

        while len(d):
            dist,x, y, z, vec = heappop(d)
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if 0 <= nx < h and 0 <= ny < w:
                    if maze[nx][ny] != '@' and distance[nx][ny] == INF:
                        if vec == i and z > 0:
                            if dist<distance[nx][ny]:
                                heappush(d,(dist,nx,ny,z-1,i))
                                distance[nx][ny]=dist
                        else:
                            if dist+1<distance[nx][ny]:
                                heappush(d,(dist+1,nx, ny, k - 1, i))
                                distance[nx][ny] = dist+1

        return distance[gx][gy]

    return bfs()

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

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

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,k):

    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,k-1,-1))
        distance[sx][sy] =0

        while len(d):
            x, y,z,vec = d.pop()

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

    return bfs()

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

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

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,k):

    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,k,-1))
        distance[sx][sy] =0

        while len(d):
            x, y,z,vec = d.pop()

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

    return bfs()

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

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
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+2)] for j in range(h+2)]
    #    distance = [[None]*field_x_length]*field_y_length
    def bfs():
        # 来た点と方向と何回同じ方向に進んだかを格納
        d = deque()
        d.append((sx, sy,k,-1))
        distance[sx][sy] =0

        while len(d):
            x, y,z,vec = d.pop()
            if x == gx and y == gy:
                return distance[gx][gy]

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

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

if not ans:
    print(-1)
else:
    print(ans+1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
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+2)] for j in range(h+2)]
    #    distance = [[None]*field_x_length]*field_y_length
    def bfs():
        # きた点と方向を格納
        d = deque()
        d.append((sx, sy,-1))
        distance[sx][sy] =0

        while len(d):
            x, y,z = d.pop()
            if x == gx and y == gy:
                return distance[gx][gy]

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

    return bfs()

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

if not ans:
    print(-1)
else:
    print(ans+1)

Submission status: Wrong Answer

Solution code:
#import time 
#it = time.time()
from heapq import heapify,heappush,heappop
import sys

def conv_4(s):
  return [s,s,s,s]

H, W, K = map(int,input().split()) #南北、東西、可動範囲
xs, ys, xg, yg = map(int,input().split()) 

#グラフを作る　
graph0 = [[["@"]*4]*(W+2)]
graph1 = [[["@"]*4]+ list(map(conv_4, input())) +[["@"]*4] for _ in range(H)]
graph = graph0 + graph1 + graph0 #はすで囲まれた盤面

#or a in graph:
#  print(a)

#Dijkstra法による探索  頂点：（座標、向き(s0,n1,e2,w3)）

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

cost=[[[(-1,0) for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

# Dijkstra Loop
while True:
  while True:#未確定の点が取り出されるまで試す
    if len(q) == 0:
      break
    c, a, s = heappop(q)
    #print(q,graph[s[0]][s[1]][s[2]])
    if graph[s[0]][s[1]][s[2]] == ".":
      break
  #print(q)
  if (len(q) == 0):
    break#未確定要素がなくなったら終了
    
  cost[s[0]][s[1]][s[2]] = (c,a) #確定したコストの値を書き込む
  graph[s[0]][s[1]][s[2]] = "@"#確定させる場所にはすを置き、二度と訪れないようにする
  #print((c,a,s))
  if ((s[0],s[1])==(xg,yg)):
    break#到達したら終了
    
  #進行方向に移動する場合
  if s[2] == 0:#南向き
    s_next = (s[0]+1,s[1],0)
  if s[2] == 1:#北向き
    s_next = (s[0]-1,s[1],1)
  if s[2] == 2:#東向き
    s_next = (s[0],s[1]+1,2)
  if s[2] == 3:#にし向き
    s_next = (s[0],s[1]-1,3)
  if graph[s_next[0]][s_next[1]][s_next[2]] == ".":
    if a < K:
      heappush(q,(c,a+1,s_next))#勢いを１失って、移動
    else:
      heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
    
  #進行方向を変更する場合
  for d in range(3):#それぞれの向きについて
    s_next = (s[0],s[1],d)
    if graph[s_next[0]][s_next[1]][s_next[2]] == ".":
      heappush(q,(c+1,0,s_next))#再び水を掻く。

#cost 出力
#print(cost[xg][yg])
ans = -1
for i in range(4):
  if ans == -1 and cost[xg][yg][i][0] >= 0:
    ans = cost[xg][yg][i][0]
    #print(ans)
  elif ans >= 0 and 0 <= cost[xg][yg][i][0] < ans:
    ans = cost[xg][yg][i][0]
print(ans)

Submission status: Wrong Answer

Solution code:
#import time 
#it = time.time()
from heapq import heapify,heappush,heappop
import sys

def conv_4(s):
  return [s,s,s,s]

H, W, K = map(int,input().split()) #南北、東西、可動範囲
xs, ys, xg, yg = map(int,input().split()) 

#グラフを作る　
graph0 = [[["@"]*4]*(W+2)]
graph1 = [[["@"]*4]+ list(map(conv_4, input())) +[["@"]*4] for _ in range(H)]
graph = graph0 + graph1 + graph0 #はすで囲まれた盤面

#or a in graph:
#  print(a)

#Dijkstra法による探索  頂点：（座標、向き(s0,n1,e2,w3)）

q=[]#未確定の頂点を格納しておく。
heappush(q,(1,0,(xs,ys,0))) #座標と向き(s0,n1,e2,w3)
heappush(q,(1,0,(xs,ys,1)))
heappush(q,(1,0,(xs,ys,2)))
heappush(q,(1,0,(xs,ys,3)))

cost=[[[(-1,0) for _ in range(4)] for _ in range(W+2)] for _ in range(H+2)]

# Dijkstra Loop
while True:
  while True:#未確定の点が取り出されるまで試す
    if len(q) == 0:
      break
    c, a, s = heappop(q)
    #print(q,graph[s[0]][s[1]][s[2]])
    if graph[s[0]][s[1]][s[2]] == ".":
      break
  #print(q)
  if (len(q) == 0):
    break#未確定要素がなくなったら終了
    
  cost[s[0]][s[1]][s[2]] = (c,a) #確定したコストの値を書き込む
  graph[s[0]][s[1]][s[2]] = "@"#確定させる場所にはすを置き、二度と訪れないようにする
  #print((c,a,s))
  if ((s[0],s[1])==(xg,yg)):
    break#到達したら終了
    
  #進行方向に移動する場合
  if s[2] == 0:#南向き
    s_next = (s[0]+1,s[1],0)
  if s[2] == 1:#北向き
    s_next = (s[0]-1,s[1],1)
  if s[2] == 2:#東向き
    s_next = (s[0],s[1]+1,2)
  if s[2] == 3:#にし向き
    s_next = (s[0],s[1]-1,3)
  if graph[s_next[0]][s_next[1]][s_next[2]] == ".":
    if a < K:
      heappush(q,(c,a+1,s_next))#勢いを１失って、移動
    else:
      heappush(q,(c+1,1,s_next))#再び水を掻いて、移動
    
  #進行方向を変更する場合
  for d in range(3):#それぞれの向きについて
    s_next = (s[0],s[1],d)
    if graph[s_next[0]][s_next[1]][s_next[2]] == ".":
      heappush(q,(c+1,0,s_next))#再び水を掻く。

#cost 出力
#print(cost[xg][yg])
ans = -1
for i in range(4):
  if ans == -1 and cost[xg][yg][i][0] >= 0:
    ans = cost[xg][yg][i][0]
    print(ans)
  elif ans >= 0 and 0 <= cost[xg][yg][i][0] < ans:
    ans = cost[xg][yg][i][0]
print(ans)