题目描述
给定一个 n 行 m 列的地牢,其中 '.' 表示可以通行的位置,'X' 表示不可通行的障碍,牛牛从 (x0 , y0 ) 位置出发,遍历这个地牢,和一般的游戏所不同的是,他每一步只能按照一些指定的步长遍历地牢,要求每一步都不可以超过地牢的边界,也不能到达障碍上。地牢的出口可能在任意某个可以通行的位置上。牛牛想知道最坏情况下,他需要多少步才可以离开这个地牢。
输入描述:
每个输入包含 1 个测试用例。每个测试用例的第一行包含两个整数 n 和 m(1 <= n, m <= 50),表示地牢的长和宽。接下来的 n 行,每行 m 个字符,描述地牢,地牢将至少包含两个 '.'。接下来的一行,包含两个整数 x0, y0,表示牛牛的出发位置(0 <= x0 < n, 0 <= y0 < m,左上角的坐标为 (0, 0),出发位置一定是 '.')。之后的一行包含一个整数 k(0 < k <= 50)表示牛牛合法的步长数,接下来的 k 行,每行两个整数 dx, dy 表示每次可选择移动的行和列步长(-50 <= dx, dy <= 50)
输出描述:
输出一行一个数字表示最坏情况下需要多少次移动可以离开地牢,如果永远无法离开,输出 -1。以下测试用例中,牛牛可以上下左右移动,在所有可通行的位置.上,地牢出口如果被设置在右下角,牛牛想离开需要移动的次数最多,为3次。
示例1
输入
3 3 ... ... ... 0 1 4 1 0 0 1 -1 0 0 -1
输出
3
【解决】
① 题意读懂很重要!!!
找到地狱中从起点到任一终点的最短路径的最大值,使用bfs实现。
public class DiYuTaoTuo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();//行
int m = sc.nextInt();//列
char[][] dungeon = new char[n][m];//迷宫
for (int i = 0;i < n;i ++){
String tmp = sc.next();
dungeon[i] = tmp.toCharArray();
}
int x0 = sc.nextInt();
int y0 = sc.nextInt();//起点
int k = sc.nextInt();//步长的个数
int[][] dxy = new int[k][2];//步长
for (int i = 0;i < k;i ++){
dxy[i][0] = sc.nextInt();
dxy[i][1] = sc.nextInt();
}
int maxDistance = bfs(dungeon,x0,y0,n,m,k,dxy);
System.out.println(maxDistance);
}
}
public static int bfs(char[][] dungeon,int x0,int y0,int n,int m,int k,int[][] dxy){
int[][] distance = new int[n][m];//保存起点到终点的步长
Queue<Integer> queueX = new LinkedList<>();
Queue<Integer> queueY = new LinkedList<>();
queueX.offer(x0);
queueY.offer(y0);
distance[x0][y0] = 1;
while (! queueX.isEmpty() && ! queueY.isEmpty()){
x0 = queueX.poll();
y0 = queueY.poll();
for (int i = 0;i < k;i ++){
if (x0 + dxy[i][0] >= 0 && x0 + dxy[i][0] < n && y0 + dxy[i][1] >= 0 && y0 + dxy[i][1] < m){//判断是否越界
if (distance[x0 + dxy[i][0]][y0 + dxy[i][1]] == 0){//判断是否已经遍历过
if (dungeon[x0 + dxy[i][0]][y0 + dxy[i][1]] == '.'){//判断是否能通过
queueX.offer(x0 + dxy[i][0]);
queueY.offer(y0 + dxy[i][1]);
distance[x0 + dxy[i][0]][y0 + dxy[i][1]] = distance[x0][y0] + 1;//更新距离和队列
}else {
distance[x0 + dxy[i][0]][y0 + dxy[i][1]] = -1;
}
}
}
}
}
int maxDistance = 0;//最大最短路径
int hasRoad = 1;//标识是否存在永远无法离开的节点
for (int i = 0;i < n;i ++){
for (int j = 0;j < m;j ++){
if (distance[i][j] == 0 && dungeon[i][j] == '.'){
hasRoad = 0;
}
maxDistance = Math.max(maxDistance,distance[i][j]);
}
}
if (hasRoad == 0){
return -1;
}else {
return maxDistance - 1;
}
}
}