진영이는 다이어트를 위해 N×M 크기의 체육관을 달리려고 한다. 체육관은 1×1 크기의 칸으로 나누어져 있고, 칸은 빈 칸 또는 벽이다. x행 y열에 있는 칸은 (x, y)로 나타낸다.
매 초마다 진영이는 위, 아래, 오른쪽, 왼쪽 중에서 이동할 방향을 하나 고르고, 그 방향으로 최소 1개, 최대 K개의 빈 칸을 이동한다.
시작점 (x1, y1)과 도착점 (x2, y2)가 주어졌을 때, 시작점에서 도착점으로 이동하는 최소 시간을 구해보자.
첫째 줄에 체육관의 크기 N과 M, 1초에 이동할 수 있는 칸의 최대 개수 K가 주어진다.
둘째 줄부터 N개의 줄에는 체육관의 상태가 주어진다. 체육관의 각 칸은 빈 칸 또는 벽이고, 빈 칸은 '.', 벽은 '#'으로 주어진다.
마지막 줄에는 네 정수 x1, y1, x2, y2가 주어진다. 두 칸은 서로 다른 칸이고, 항상 빈 칸이다.
(x1, y1)에서 (x2, y2)로 이동하는 최소 시간을 출력한다. 이동할 수 없는 경우에는 -1을 출력한다.
import java.util.*;
import java.io.*;
public class Main {
static int N, M, K;
static char[][] arr;
static int[][] visited;
static int[] dx = { -1, 1, 0, 0 };
static int[] dy = { 0, 0, 1, -1 };
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
arr = new char[N][M];
visited = new int[N][M];
for (int i = 0; i < N; i++) {
String s = br.readLine();
Arrays.fill(visited[i], Integer.MAX_VALUE);
for (int j = 0; j < M; j++) {
arr[i][j] = s.charAt(j);
}
}
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken())-1;
int y = Integer.parseInt(st.nextToken())-1;
Node start = new Node(x, y);
x = Integer.parseInt(st.nextToken())-1;
y = Integer.parseInt(st.nextToken())-1;
Node end = new Node(x, y);
BFS(start, end);
System.out.println(visited[end.x][end.y] == Integer.MAX_VALUE ? -1 : visited[end.x][end.y]);
}
public static void BFS(Node start, Node end) {
Queue<Node> q = new LinkedList<>();
q.add(start);
visited[start.x][start.y] = 0;
while(!q.isEmpty()) {
Node n = q.poll();
if (n.x == end.x && n.y == end.y) {
return ;
}
for (int i = 0; i < 4; ++i) {
for (int k = 1; k <= K; ++k) {
int nx = n.x + dx[i] * k;
int ny = n.y + dy[i] * k;
if (nx < 0 || ny < 0 || nx >= N || ny >= M || arr[nx][ny] == '#') {
break;
}
if (visited[nx][ny] < visited[n.x][n.y] + 1)
break;
if (arr[nx][ny] == '.' && visited[nx][ny] == Integer.MAX_VALUE) {
q.add(new Node(nx, ny));
visited[nx][ny] = visited[n.x][n.y]+1;
}
}
}
}
}
}
class Node {
int x, y;
Node (int x, int y) {
this.x = x;
this.y = y;
}
}