题意翻译
题目描述
有一NxM的迷宫,'#'是墙,‘.’是路,一秒钟可以向四个方向中的一个移动1~k步,求从起点到终点的最短时间。
输入格式:
第一行n、m、k,下面是NxM的迷宫,最后是起点到终点的坐标。
输出格式:
输出最短时间。如果不能离开迷宫,输出-1。
输入输出样例
输入 #1复制
3 4 4 .... ###. .... 1 1 3 1
输出 #1复制
3
输入 #2复制
3 4 1 .... ###. .... 1 1 3 1
输出 #2复制
8
输入 #3复制
2 2 1 .# #. 1 1 2 2
输出 #3复制
-1
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int[] dx = {0, -1, 1, 0, 0};
static int[] dy = {0, 0, 0, -1, 1};
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
char[][] a = new char[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
String s = sc.next();
for (int j = 1; j <= m; j++) {
a[i][j] = s.charAt(j - 1);
}
}
boolean[][] vis = new boolean[n + 1][m + 1];
int sx = sc.nextInt();
int sy = sc.nextInt();
int endx = sc.nextInt();
int endy = sc.nextInt();
if (sx == endx && sy == endy) {
System.out.println(0);
return;
}
Queue<Node> q = new LinkedList<>();
q.offer(new Node(sx, sy, 0));
vis[sx][sy] = true;
int ans = 0;
t:
while (!q.isEmpty()) {
Node no = q.poll();
int x = no.x;
int y = no.y;
int step = no.step;
if (x == endx && y == endy) {
ans = step + 1;
break;
}
for (int i = 1; i <= 4; i++) {
//枚举1-k能走的步数
for (int j = 1; j <= k; j++) {
int xx = x + dx[i] * j;
int yy = y + dy[i] * j;
if (xx >= 1 && yy >= 1 && xx <= n && yy <= m) {
if (vis[xx][yy]) continue;
//剪枝
if (a[xx][yy] == '#') break;
vis[xx][yy] = true;
if (xx == endx && yy == endy) {
ans = step + 1;
break t;
}
q.offer(new Node(xx, yy, step + 1));
} else {
break;
}
}
}
}
out.println(ans != 0 ? ans : -1);
out.flush();
out.close();
}
static class Node {
int x, y, step;
public Node(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
}