Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
输入格式
第一行包含两个整数 n和 m。接下来 n 行,每行包含 m 个整数(0 或 1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤100
输入样例:
5 5 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0输出样例:
8
二、思路分析:
-
这一部分考察了我们对BFS的运用,和对BFS含有最短特性的理解。
-
做题的时候需要考虑的应该是我们的边缘问题,数组很可能会越界
-
除了BFS我们还可以利用A*来解决迷宫问题,因为A星是启发式搜索我们可以通过比较节点的理想距离来跳过部分的路线。
三、AC 代码:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
/** 迷宫大小 n:行 m:列 */
public static int n,m;
/** 迷宫 */
public static int[][]g = null;
/** 点的距离 */
public static int[][]de = null;
/** 坐标类*/
public static class Dian{
public int x;
public int y;
public Dian(int x,int y){
this.x = x;
this.y = y;
}
}
/** 四个方向 */
public static int dx[] = {-1, 0, 1, 0};
public static int dy[] = {0, 1, 0, -1};
/** 队列 */
public static Queue<Dian> queue = new LinkedList<Dian>();
public static void main(String[] args) {
/** 读取迷宫的大小*/
Scanner in = new Scanner(System.in);
n = in.nextInt(); m = in.nextInt();
/** 初始化数组 */
g = new int[n][m];
de = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
g[i][j] = in.nextInt();
de[i][j] = -1;
}
}
int sum = bfs();
System.out.println(sum);
}
public static int bfs(){
queue.add(new Dian(0, 0));
de[0][0] = 0;
while(!queue.isEmpty()){
Dian tmp = queue.remove();
for (int i = 0; i < 4; i++) {
int x = tmp.x + dx[i];
int y = tmp.y + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && de[x][y] == -1) {
de[x][y] = de[tmp.x][tmp.y] + 1;
queue.add(new Dian(x, y));
}
}
}
return de[n - 1][m - 1];
}
}
四、总结:
考察了我们对BFS的基本运用。我看有一些同学喜获使用DFS来解决迷宫问题,其实可以转化一下心态使用BFS的最短性来解决。