import java.util.Arrays;
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[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
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}
};
dfs(0, 0, 0, map);
}
public static void dfs(int x, int y, int step, int[][] map) {
if (step >= (map.length) * (map[0].length - 1)) {
return;
}
visit[x][y] = 1;
if (x == ex && y == ey) {
minStep = step < minStep ? step : minStep;
print(); // 打印标记为1的路线结果
System.out.println("最小步骤: " + minStep);
return;
}
for (int[] offset : DIRECTIONS) {
int newX = x + offset[0];
int newY = y + 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;
dfs(newX, newY, step + 1, map);
visit[newX][newY] = 0;
}
}
}
public static void print() {
for (int[] tt : visit) {
System.out.println(Arrays.toString(tt));
}
}
}
dfs 走迷宫
于 2023-09-15 15:23:27 首次发布