栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

    

    static int BFS(Pair start,Pair end) {
        //定义队列
        LinkedList 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;ihealth || 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;}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号