Problem:


Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1



Sample input:
3 5 2
3 2 3 4
.....
.@..@
..@..


Sample output:
5

Submission status: Time Limit Exceeded

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


def main():
    h, w, k = map(int, input().split())
    sx, sy, gx, gy = map(int, input().split())
    pond = [input().replace("\n", "") for _ in range(h)]
    
    dist_N = [[None]*w for _ in range(h)]
    dist_S = [[None]*w for _ in range(h)]
    dist_E = [[None]*w for _ in range(h)]
    dist_W = [[None]*w for _ in range(h)]
    
    not_yet = [(0, k-1, sx-1, sy-1, "N")]
    
    while not_yet:
        a, b, x, y, d = heappop(not_yet)
        if d == "N" and dist_N[x][y] == None:
            dist_N[x][y] = (a, b)
            if x > 0 and pond[x-1][y] == "." and dist_N[x-1][y] == None:
                if b == k-1:
                    not_yet.append((a+1, 0, x-1, y, "N"))
                else:
                    not_yet.append((a, b+1, x-1, y, "N"))
            if x < h-1 and pond[x+1][y] == "." and dist_S[x+1][y] == None:
                not_yet.append((a+1, 0, x+1, y, "S"))
            if y > 0 and pond[x][y-1] == "." and dist_W[x][y-1] == None:
                not_yet.append((a+1, 0, x, y-1, "W"))
            if y < w-1 and pond[x][y+1] == "." and dist_E[x][y+1] == None:
                not_yet.append((a+1, 0, x, y+1, "E"))
        if d == "W" and dist_W[x][y] == None:
            dist_W[x][y] = (a, b)
            if x > 0 and pond[x-1][y] == "." and dist_N[x-1][y] == None:
                not_yet.append((a+1, 0, x-1, y, "N"))
            if x < h-1 and pond[x+1][y] == "." and dist_S[x+1][y] == None:
                not_yet.append((a+1, 0, x+1, y, "S"))
            if y > 0 and pond[x][y-1] == "." and dist_W[x][y-1] == None:
                if b == k-1:
                    not_yet.append((a+1, 0, x, y-1, "W"))
                else:
                    not_yet.append((a, b+1, x, y-1, "W"))
            if y < w-1 and pond[x][y+1] == "." and dist_E[x][y+1] == None:
                not_yet.append((a+1, 0, x, y+1, "E"))
        if d == "S" and dist_S[x][y] == None:
            dist_S[x][y] = (a, b)
            if x > 0 and pond[x-1][y] == "." and dist_N[x-1][y] == None:
                not_yet.append((a+1, 0, x-1, y, "N"))
            if x < h-1 and pond[x+1][y] == "." and dist_S[x+1][y] == None:
                if b == k-1:
                    not_yet.append((a+1, 0, x+1, y, "S"))
                else:
                    not_yet.append((a, b+1, x+1, y, "S"))
            if y > 0 and pond[x][y-1] == "." and dist_W[x][y-1] == None:
                not_yet.append((a+1, 0, x, y-1, "W"))
            if y < w-1 and pond[x][y+1] == "." and dist_E[x][y+1] == None:
                not_yet.append((a+1, 0, x, y+1, "E"))
        if d == "E" and dist_E[x][y] == None:
            dist_E[x][y] = (a, b)
            if x > 0 and pond[x-1][y] == "." and dist_N[x-1][y] == None:
                not_yet.append((a+1, 0, x-1, y, "N"))
            if x < h-1 and pond[x+1][y] == "." and dist_S[x+1][y] == None:
                not_yet.append((a+1, 0, x+1, y, "S"))
            if y > 0 and pond[x][y-1] == "." and dist_W[x][y-1] == None:
                not_yet.append((a+1, 0, x, y-1, "W"))
            if y < w-1 and pond[x][y+1] == "." and dist_E[x][y+1] == None:
                if b == k-1:
                    not_yet.append((a+1, 0, x, y+1, "E"))
                else:
                    not_yet.append((a, b+1, x, y+1, "E"))
        
    gx -= 1
    gy -= 1
    ans = [10**7]
    
    for v in [dist_N[gx][gy], dist_S[gx][gy], dist_E[gx][gy], dist_W[gx][gy]]:
        if v != None:
            ans.append(v[0])
    
    answer = min(ans)
    print(-1 if answer == 10**7 else answer)
    
        
        
        
    
    
    
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

H, W, K = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = y1-1, x1-1, y2-1, x2-1

grid = []
for _ in range(H):
    grid.append(sys.stdin.readline().strip())

# x, y = i（曲がった回数）を保持する
visited = {}
# x, y, i, d（進んでいる方向）, j（曲がらずに進んでいる距離）
# aは例外で全方向に曲がらずに進める
q = deque([(x1, y1, 1, "a", 0)])
ans = float("inf")
while q:
    x, y, i, d, j = q.popleft()
    if (x, y) in visited and visited[(x, y)] < i:
        continue
    visited[(x, y)] = i
    # print(x, y, i, j, d)

    for dx, dy, dd in ((1,0,"e"), (-1,0,"w"), (0,1,"s"), (0,-1,"n")):
        nx = x + dx
        ny = y + dy
        ni = i
        nj = j
        if 0 <= nx < W and 0 <= ny < H and grid[ny][nx] == ".":
            if (d == "a" or dd == d) and nj < K:
                nj += 1
            else:
                ni += 1
                nj = 1
            if nx == x2 and ny == y2:
                ans = min(ans, ni)
                continue
            # q.append((nx, ny, ni, dd, nj))
            q.appendleft((nx, ny, ni, dd, nj))

print(-1 if ans == float("inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

H, W, K = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = y1-1, x1-1, y2-1, x2-1

grid = []
for _ in range(H):
    grid.append(sys.stdin.readline().strip())

# x, y = i（曲がった回数）を保持する
visited = {}
# x, y, i, d（進んでいる方向）, j（曲がらずに進んでいる距離）
# aは例外で全方向に曲がらずに進める
q = deque([(x1, y1, 1, "a", 0)])
ans = float("inf")
while q:
    x, y, i, d, j = q.popleft()
    if (x, y) in visited and visited[(x, y)] <= i:
        continue
    visited[(x, y)] = i
    # print(x, y, i, j, d)

    for dx, dy, dd in ((1,0,"e"), (-1,0,"w"), (0,1,"s"), (0,-1,"n")):
        nx = x + dx
        ny = y + dy
        ni = i
        nj = j
        if 0 <= nx < W and 0 <= ny < H and grid[ny][nx] == ".":
            if (d == "a" or dd == d) and nj < K:
                nj += 1
            else:
                ni += 1
                nj = 1
            if nx == x2 and ny == y2:
                ans = min(ans, ni)
                continue
            q.append((nx, ny, ni, dd, nj))

print(-1 if ans == float("inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

H, W, K = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = map(int, sys.stdin.readline().split())
y1, x1, y2, x2 = y1-1, x1-1, y2-1, x2-1

grid = []
for _ in range(H):
    grid.append(sys.stdin.readline().strip())

# x, y = i（曲がった回数）を保持する
visited = {}
# x, y, i, d（進んでいる方向）, j（曲がらずに進んでいる距離）
# aは例外で全方向に曲がらずに進める
q = deque([(x1, y1, 1, "a", 0)])
ans = float("inf")
while q:
    x, y, i, d, j = q.popleft()
    if (x, y) in visited and visited[(x, y)] < i:
        continue
    visited[(x, y)] = i
    # print(x, y, i, j, d)

    for dx, dy, dd in ((1,0,"e"), (-1,0,"w"), (0,1,"s"), (0,-1,"n")):
        nx = x + dx
        ny = y + dy
        ni = i
        nj = j
        if 0 <= nx < W and 0 <= ny < H and grid[ny][nx] == ".":
            if (d == "a" or dd == d) and nj < K:
                nj += 1
            else:
                ni += 1
                nj = 1
            if nx == x2 and ny == y2:
                ans = min(ans, ni)
                continue
            q.append((nx, ny, ni, dd, nj))

print(-1 if ans == float("inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

H, W, K = mapint()
y1, x1, y2, x2 = mapint()
pond = [list(input()) for _ in range(H)]
from collections import deque
Q = deque([(y1-1, x1-1)])

inf = 10**18
dist = [[inf]*W for _ in range(H)]
dist[y1-1][x1-1] = 0
while Q:
    y, x = Q.popleft()
    if y==y2-1 and x==x2-1:
        break
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        for i in range(1, K+1):
            ny, nx = y+dy*i, x+dx*i
            if ny<0 or ny>=H or nx<0 or nx>=W:
                break
            if pond[ny][nx]=='@':
                break
            if dist[ny][nx]<dist[y][x]:
                break
            if dist[ny][nx]>dist[y][x]+1:
                dist[ny][nx] = dist[y][x]+1
                Q.append((ny, nx))
if dist[y2-1][x2-1]>=10**17:
    print(-1)
else:
    print(dist[y2-1][x2-1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import deque

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

    adj = [[] for _ in range(W*H)]
    dx = [1,-1,0,0]
    dy = [0,0,1,-1]
    
    for i in range(H):
        for j in range(W):
            if c[i][j] == '@': continue
            for k in range(4):
                y = i + dy[k]
                x = j + dx[k]
                if 0 <= y < H and 0 <= x < W and c[y][x] == '.':
                    adj[W*i+j].append(W*y+x)
    
    queue = deque([W*x1+y1])
    visit = [-1] * (W*H)
    visit[W*x1+y1] = 0
    
    while queue:
        now = queue.popleft()
        for u in adj[now]:
            # nowからuの方向に'.'が続くかぎり（最大K個）
            count = 0
            direct = u - now
            fromC = now
            toC = u
            while count < K and toC in adj[fromC]:
                count += 1
                if visit[toC] < 0:
                    queue.append(toC)
                    visit[toC] = visit[now] + 1
                fromC = toC
                toC += direct 

    print(visit[W*x2+y2])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import deque

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

    adj = [[] for _ in range(W*H)]
    dx = [1,-1,0,0]
    dy = [0,0,1,-1]
    
    for i in range(H):
        for j in range(W):
            if c[i][j] == '@': continue
            for k in range(4):
                y = i + dy[k]
                x = j + dx[k]
                if 0 <= y < H and 0 <= x < W and c[y][x] == '.':
                    adj[W*i+j].append(W*y+x)
    
    queue = deque([W*x1+y1])
    visit = [-1] * (W*H)
    visit[W*x1+y1] = 0
    
    while queue:
        now = queue.popleft()
        for u in adj[now]:
            # nowからuの方向に'.'が続くかぎり（最大K個）
            count = 0
            direct = u - now
            fromC = now
            toC = u
            while count < K and toC in adj[fromC]:
                count += 1
                if visit[toC] < 0:
                    queue.append(toC)
                    visit[toC] = visit[now] + 1
                fromC = toC
                toC += direct 

    print(visit[W*x2+y2])
    # print(visit)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())

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

maze=[list(input()) for _ in range(h)]

from collections import deque
stack=deque([(y1-1,x1-1)])

before=[[0]*w for _ in range(h)]
dic={}
dic[0]=0
dic[(0,1)]=(0,-1)
dic[(0,-1)]=(0,1)
dic[(1,0)]=(-1,0)
dic[(-1,0)]=(1,0)

maze[y1-1][x1-1]=0
#pri(maze)
while len(stack)>0:
    #print(stack)
    (y,x)=stack.popleft()
    if (y,x)==(y2-1,x2-1):
        print(maze[y][x])
        exit()

    #縦横左右
    for (my,mx) in ((1,0),(0,1),(-1,0),(0,-1)):
        #print(my,mx)
        flag=0
        if (my,mx)!=dic[before[y][x]]:
            for kk in range(1,k+1):
                ny=y+my*kk
                nx=x+mx*kk
                if 0<=ny<h and 0<=nx<w:
                    if maze[ny][nx]!="@":
                        if maze[ny][nx]==".":
                            maze[ny][nx]=maze[y][x]+1
                            stack.append((ny,nx))
                            before[ny][nx]=((my,mx))
                    else:
                        break
                else:
                    break
    #pri(maze)
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
      if tx == gx and ty == gy:
        print(reach[gx][gy])
        exit()
#print(reach)
#ans = reach[gx][gy]
#if ans == INF:
print(-1)
#else:
#  print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
      if tx == gx and ty == gy:
        print(reach[gx][gy])
        exit()
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
    if tx == gx and ty == gy:
      print(reach[gx][gy])
      exit()
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append((sx,sy))
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append((tx,ty))
    if tx == gx and ty == gy:
      print(reach[gx][gy])
      exit()
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())

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

maze=[list(input()) for _ in range(h)]

from collections import deque
stack=deque([(y1-1,x1-1)])

def pri(x):
    print("MAZE###########")
    for item in x:
        print(item)

maze[y1-1][x1-1]=0
#pri(maze)
while len(stack)>0:
    #print(stack)
    (y,x)=stack.popleft()
    if (y,x)==(y2-1,x2-1):
        print(maze[y][x])
        exit()

    #縦横左右
    for (my,mx) in [(1,0),(0,1),(-1,0),(0,-1)]:
        #print(my,mx)
        flag=0
        for kk in range(1,k+1):
            ny=y+my*kk
            nx=x+mx*kk
            if 0<=ny<h and 0<=nx<w:
                if maze[ny][nx]!="@":
                    if maze[ny][nx]==".":
                        maze[ny][nx]=maze[y][x]+1
                        stack.append((ny,nx))
                else:
                    break
            else:
                break
    #pri(maze)
print(-1)

Submission status: Time Limit Exceeded

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())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append([sx,sy])
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    tx,ty = nx,ny
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append([tx,ty])
  if nx == gx and ny == gy:
    print(reach[gx][gy])
    exit()
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w,k=map(int,input().split())

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

maze=[list(input()) for _ in range(h)]

from collections import deque
stack=deque([(y1-1,x1-1)])

def pri(x):
    print("MAZE###########")
    for item in x:
        print(item)

maze[y1-1][x1-1]=0
#pri(maze)
while len(stack)>0:
    #print(stack)
    (y,x)=stack.popleft()
    if (y,x)==(y2-1,x2-1):
        print(maze[y][x])
        exit()

    #縦横左右
    for (my,mx) in [(1,0),(0,1),(-1,0),(0,-1)]:
        #print(my,mx)
        flag=0
        for kk in range(1,k+1):
            ny=y+my*kk
            nx=x+mx*kk
            if 0<=ny<h and 0<=nx<w:
                if maze[ny][nx]!="@":
                    if maze[ny][nx]=="." and flag==0:
                        maze[ny][nx]=maze[y][x]+1
                        stack.append((ny,nx))
                else:
                    flag=1
                    break
            else:
                break
    #pri(maze)
print(-1)

Submission status: Time Limit Exceeded

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())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append([sx,sy])
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    tx,ty = nx,ny
    for fac in range(1,K+1):
      tx = nx + fac*dxdy[i][0]
      ty = ny + fac*dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append([tx,ty])
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
H,W,K = map(int,input().split())
sx,sy,gx,gy = map(int,input().split())
sx-=1;sy-=1;gx-=1;gy-=1
Pond = []; INF = float("inf")
for i in range(H):
  temp = str(input());temp = list(temp)
  Pond.append(temp)
#print(Pond)
Q = deque([])
Q.append([sx,sy])
reach = [[INF]*W for _ in range(H)]
reach[sx][sy] = 0
dxdy = [(1,0),(-1,0),(0,1),(0,-1)]
while Q:
  nx,ny = Q.popleft()
  step = K
  for i in range(4):
    tx,ty = nx,ny
    step = K
    while step > 0:
      tx += dxdy[i][0]
      ty += dxdy[i][1]
      #print(i,tx,ty)
      if 0>tx or tx>=H or 0>ty or ty>=W or Pond[tx][ty] == "@": #or reach[tx][ty] != INF:
        #print(i,tx,ty,reach[2][0])
        break #範囲外やハスがあった、到達済みの場合には終了
      #print(i,tx,ty)
      if reach[nx][ny] + 1 > reach[tx][ty]: #もし現時点よりもステップが大きい場合はだめ。
        #同じ場合は向き的に得している場合もあるので残す。
        break
      reach[tx][ty] = reach[nx][ny] + 1
      Q.append([tx,ty])
      step -= 1
#print(reach)
ans = reach[gx][gy]
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

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

def bfs(sl, visited, sy, sx, gy, gx, h, w, k):
    q = deque([ (sy,sx) ])
    visited[sy][sx] = 0
    while q:
        # print(q)
        y, x = q.popleft()
        if [y, x] == [gy, gx]:
            return visited[gy][gx]
        for i in range(1,k+1):
            ny = y+i
            if ny >= h:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            visited[ny][x] = visited[y][x]+1
            q.append((ny,x))

        for i in range(1,k+1):
            ny = y-i
            if ny < 0:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            visited[ny][x] = visited[y][x]+1
            q.append((ny,x))

        for i in range(1,k+1):
            nx = x+i
            if nx >= w:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            visited[y][nx] = visited[y][x]+1
            q.append((y,nx))

        for i in range(1,k+1):
            nx = x-i
            if nx < 0:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            visited[y][nx] = visited[y][x]+1
            q.append((y,nx))

    return -1

def main():
    h,w,k = map(int, input().split())
    x1,y1,x2,y2 = map(int, input().split())
    cl = []
    for i in range(h):
        row = list(input())
        cl.append(row)

    visited = [ [-1]*w for i in range(h)]
    ans = bfs(cl, visited, x1-1,y1-1,x2-1,y2-1,h,w,k)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs(sl, visited, sy, sx, gy, gx, h, w, k):
    q = deque([[sy,sx]])
    visited[sy][sx] = 0
    while q:
        # print(q)
        y, x = q.popleft()
        if [y, x] == [gy, gx]:
            return visited[gy][gx]
        for i in range(1,k+1):
            ny = y+i
            if ny >= h:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            visited[ny][x] = visited[y][x]+1
            q.append([ny,x])

        for i in range(1,k+1):
            ny = y-i
            if ny < 0:
                break
            if sl[ny][x] == '@':
                break
            if 0 <= visited[ny][x] <= visited[y][x]:
                break
            visited[ny][x] = visited[y][x]+1
            q.append([ny,x])

        for i in range(1,k+1):
            nx = x+i
            if nx >= w:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            visited[y][nx] = visited[y][x]+1
            q.append([y,nx])

        for i in range(1,k+1):
            nx = x-i
            if nx < 0:
                break
            if sl[y][nx] == '@':
                break
            if 0 <= visited[y][nx] <= visited[y][x]:
                break
            visited[y][nx] = visited[y][x]+1
            q.append([y,nx])

    return -1

def main():
    h,w,k = map(int, input().split())
    x1,y1,x2,y2 = map(int, input().split())
    cl = []
    for i in range(h):
        row = list(input())
        cl.append(row)

    visited = [ [-1]*w for i in range(h)]
    ans = bfs(cl, visited, x1-1,y1-1,x2-1,y2-1,h,w,k)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
h,w,k=list(map(int,input().split()))
sx,sy,ex,ey=list(map(int,input().split()))
sx,sy,ex,ey=sx-1,sy-1,ex-1,ey-1
c=[]
for i in range(h):
  cc=[]
  for j in input():
    if j==".":
      cc.append(0)
    else:
      cc.append(1)
  c.append(cc)


l=[]
for i in range(h):
  l.append([0 for j in range(w)])

l[sx][sy]=1
def chp(x,y):
  if (x<0)or(x>=h)or(y<0)or(y>=w):
    return True
  else:
    return False

nc=[[sx,sy]]
dat=[[1,0],[-1,0],[0,1],[0,-1]]
f=0
cnt=0
while True:
  if len(nc)==0:
    break
  cnt+=1
  nnc=[]
  for i in nc:
    for j in dat:
      for g in range(1,k+1):
        cx,cy=i[0]+g*j[0],i[1]+g*j[1]
        if chp(cx,cy) or c[cx][cy]:
          break
        if l[cx][cy]==0:
          nnc.append([cx,cy])
          if cx==ex and cy==ey:
            f=1
            print(cnt)
            break
          l[cx][cy]=1
      if f:
        break
    if f:
      break
  if f:
    break
  nc=nnc
if f==0:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq
        from collections import defaultdict

        hq = []
        direction = {0: (1, 0), 2: (-1, 0), 1: (0, 1), 3: (0, -1)}
        dist = [[[INF] * 4 for _ in range(w + 2)] for _ in range(h + 2)]
        for d in range(4):
            heapq.heappush(hq, (0, x1, y1, d))
            dist[x1][y1][d] = 0
        cnt = 0

        while hq:
            cnt += 1
            cost, cx, cy, cd = heapq.heappop(hq)

            for d in range(4):
                if cd % 2 == d % 2:
                    continue
                new_cost = (cost + k - 1) // k * k
                if new_cost < dist[cx][cy][d]:
                    dist[cx][cy][d] = new_cost
                    heapq.heappush(hq, (new_cost, cx, cy, d))

            new_cost = cost + 1
            nx, ny = cx + direction[cd][0], cy + direction[cd][1]
            if grid[nx][ny] == "." and new_cost < dist[nx][ny][cd]:
                heapq.heappush(hq, (new_cost, nx, ny, cd))
                dist[nx][ny][cd] = new_cost

        x = INF
        for d in range(4):
            x = min(x, dist[x2][y2][d])
        if x == INF:
            return -1
        else:
            return (x + k - 1) // k

    ans = bfs()
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    h, w, k = map(int, readline().split())
    x1, y1, x2, y2 = map(int, readline().split())
    grid = [["@"] * (w + 2)]
    for _ in range(h):
        s = ["@"] + list(input()) + ["@"]
        grid.append(s)
    grid.append(["@"] * (w + 2))

    def bfs():
        import heapq
        from collections import defaultdict

        hq = []

        dist = defaultdict(lambda: INF)
        for d in "NEWS":
            heapq.heappush(hq, (0, x1, y1, d))
            dist[(x1, y1, d)] = 0
        op = {"N": "S", "S": "N", "E": "W", "W": "E", "C": "X"}

        while hq:
            cost, cx, cy, cd = heapq.heappop(hq)
            for d in "NEWS":
                if d == cd:
                    continue
                new_cost = (cost + k - 1) // k * k
                dist[(cx, cy, d)] = new_cost

            for mx, my, md in ((1, 0, "N"), (-1, 0, "S"), (0, 1, "E"), (0, -1, "W")):
                if cd == md:
                    new_cost = cost + 1
                else:
                    new_cost = (cost + k - 1) // k * k + 1

                nx, ny = cx + mx, cy + my
                if grid[nx][ny] == ".":
                    if new_cost < dist[(nx, ny, md)]:
                        heapq.heappush(hq, (new_cost, nx, ny, md))
                        dist[(nx, ny, md)] = new_cost
        x = INF
        for d in "NEWS":
            x = min(x, dist[(x2, y2, d)])
        if x == INF:
            return -1
        else:
            return (x + k - 1) // k

    ans = bfs()
    print(ans)


if __name__ == '__main__':
    main()