bfs 走迷宫

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));
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值