版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013803572/article/details/82936562
迷宫算法,宽度优先搜索Java实现
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
5 5
1 1 0 1 1
0 1 0 1 0
0 1 1 1 0
0 0 1 1 0
1 0 1 1 1
*
*/
public class BfsTest {
// 迷宫,0:墙, 1:路
static int[][] maze;
// 迷宫大小
static int m, n;
// 行走方向判断辅助数组,一个点可以想四个方向行走
static int[] dx = { 1, -1, 0, 0 };
static int[] dy = { 0, 0, 1, -1 };
// 保存起点到该点的最短路径
static int[][] dist = new int[100][100];
// 该点是否走过
static boolean[][] vstd = new boolean[100][100];
// 将下一步要走的路放入队列,使用队列实现递归
static List<Point> queue = new ArrayList<>();
/**
* 判断:
* 是否在迷宫内: x >= 0 && y >= 0 && x < m && y < n
* 是否没有访问过: !vstd[x][y], 访问过的路不在尝试
* 是否是路: maze[x][y] == 1
* @param x
* @param y
* @return
*/
static boolean judge(int x, int y) {
return x >= 0 && y >= 0 && x < m && y < n && !vstd[x][y] && maze[x][y] == 1 ;
}
/**
* 宽度有限搜索实现,计算七点到可以到达的点的路径步数
* @param x
* @param y
*/
public static void bfs(int x, int y) {
if(!judge(x, y)) {
return;
}
queue.add(new Point(x, y, 1));// 将起点加入队列
dist[x][y] = 1; // 设置起点步数为1
vstd[x][y] = true;// 将起点设置为已访问过
// 开始搜索
for(int i = 0; i < queue.size(); i++) {
Point currP = queue.get(i); // 取得当前起点
int currX = currP.x;
int currY = currP.y;
// 尝试起点周围四个方向的路是否可行
for(int j = 0;j < 4;j++) {
int nextX = currX + dx[j];
int nextY = currY + dy[j];
if(judge(nextX, nextY)) { // 是否可行
int step = currP.step + 1; // 计算步数
queue.add(new Point(nextX, nextY, step)); // 添加到队列中
dist[nextX][nextY] = step; // 保存步数
vstd[nextX][nextY] = true; // 标记已访问
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
m = scan.nextInt();
n = scan.nextInt();
maze = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int t = scan.nextInt();
maze[i][j] = t;
}
}
scan.close();
System.out.println("search: 2, 1");
bfs(2, 1); // 开始搜索,起点位置你可以改成从控制台输入
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(dist[i][j] + "\t");
}
System.out.println();
}
System.out.println("search: 0, 0");
queue = new ArrayList<>();
vstd = new boolean[100][100];
dist = new int[100][100];
bfs(0, 0); // 开始搜索,起点位置你可以改成从控制台输入
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(dist[i][j] + "\t");
}
System.out.println();
}
}
}
class Point {
public int x, y, step;
public Point(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
- 样例输入和输出
5 5
1 1 0 1 1
0 1 0 1 0
0 1 1 1 0
0 0 1 1 0
1 0 1 1 1
search: 2, 1
4 3 0 5 6
0 2 0 4 0
0 1 2 3 0
0 0 3 4 0
0 0 4 5 6
search: 0, 0
1 2 0 8 9
0 3 0 7 0
0 4 5 6 0
0 0 6 7 0
0 0 7 8 9