import javafx.util.Pair;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class m2 {
static int ex = 4; // 结束x坐标
static int ey = 1; // 结束y坐标
static int minStep = 999999999;
static int[][] visit = new int[5][4]; // 0未访问 1 访问
static int[][] map;// 0表示空地,1表示障碍
private final static int[][] DIRECTIONS = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public static void main(String[] args) {
int[][] map = {
{0, 1, 0, 1},
{0, 0, 0, 0},
{1, 1, 1, 0},
{1, 0, 0, 0},
{1, 0, 1, 1}
};
bfs(0, 0, 0, map);
}
public static void bfs(int x, int y, int step, int[][] map) {
Queue<Pair<Integer, Integer>> stack = new LinkedList<>();
stack.add(new Pair<>(x, y));
visit[x][y] = 1;
while (!stack.isEmpty()) {
int beforeLen = stack.size();
Pair<Integer, Integer> nowPair = stack.poll();
int x1 = nowPair.getKey();
int y1 = nowPair.getValue();
if (x1 == ex && y1 == ey) {
minStep = step < minStep ? step : minStep;
print(); // 打印标记为1的路线结果
System.out.println("最小步骤: " + minStep);
return;
}
for (int[] offset : DIRECTIONS) { // 走四个方向
int newX = x1 + offset[0];
int newY = y1 + offset[1];
if (newX >= map.length || newY >= map[0].length || newX < 0 || newY < 0) {
continue;
}
if (map[newX][newY] == 0 && visit[newX][newY] == 0) {
visit[newX][newY] = 1;
step++;
stack.add(new Pair<>(newX, newY));
}
}
if(stack.size()<beforeLen){ // 说明当前的点四个方向都走不通,把当前的点还原
visit[x1][y1] = 2; // 表示回退
step--;
}
}
}
public static void print() {
for (int[] tt : visit) {
System.out.println(Arrays.toString(tt));
}
}
}
bfs 走迷宫
于 2023-09-15 16:28:33 首次发布