0
点赞
收藏
分享

微信扫一扫

java广度优先搜索保姆级实例代码

花了一下午终于把bfs搞懂了,手写一道例题

package BFS;


import java.util.LinkedList;
import java.util.Scanner;

public class 迷宫 {

static int health,with;
static char map[][];
static Boolean mapCheck[][];

    /**
     * 空间向量
     */
   static int x[] = {0,0,1,-1};
   static int y[] = {1,-1,0,0};

    /**
     * BFS广度优先搜索
     * @param
     */

    static int BFS(Pair start,Pair end) {
        //定义队列
        LinkedList<Pair> q = new LinkedList<>();
        //将起点入队
        q.offer(start);
        while (!q.isEmpty())
        {
            Pair top = q.peek(); //取出队头并且弹出
            q.poll();
            if (top.x == end.x && top.y == end.y) return top.step;  //是否到达终点

            for (int i=0;i<x.length;i++)
            {
                int newX = top.x+x[i];
                int newY = top.y+y[i];  //枚举新的四个坐标
                if (Check(newX,newY))   //检查新坐标是否有效
                {
                    Pair New = new Pair(newX,newY);  //生成新坐标的状态
                    q.offer(New);   //入队
                    New.step = top.step+1; //更新新坐标的深度
                    mapCheck[newX][newY] =true;  //设置已经入队
                }
            }


        }
return -1;
    }

    static Boolean Check(int x,int y)
    {
       if (x>health || x<1 || y>with || y<1) return  false;  //超出坐标地图
       if (map[x][y] == '*') return false;   //障碍
       if (mapCheck[x][y] == null) return true; //没有入队
       else return false;

    }
    public static void main(String[] args) {
        /**
         * 迷宫地图长度是否入队初始化
         */
        Scanner sc = new Scanner(System.in);
         health = sc.nextInt();
         with = sc.nextInt();
         map = new char[health+1][with+1];
         mapCheck = new Boolean[health+1][with+1];
        for (int i=1;i<=health;i++)
        {
            String s = sc.next();
            for(int j = 1;j<=with;j++)
                map[i][j] = s.charAt(j-1);
        }


        /**
         * 起点和终点坐标
         */
        Pair start = new Pair(sc.nextInt()+1,sc.nextInt()+1);
        Pair end = new Pair(sc.nextInt()+1,sc.nextInt()+1);
        start.step = 0;
        System.out.println(BFS(start,end));


    }
}

/**
 * 存储每个节点的状态
 */
class Pair{
    int x,y,step;
    public Pair(int x, int y){this.x = x; this.y = y;}
}
举报

相关推荐

0 条评论