简单广度优先搜索

一次将一个节点的所有相邻节点都遍历,然后再依次遍历相邻节点的相邻节点,依此类推。
使用队列作为辅助的数据结构。
广度优先遍历求出了无权图的最短路径
迷宫问题,

import java.util.LinkedList;

import java.util.Queue;
//广度优先搜索
class MAN{
     int x;//坐标
     int y;//坐标
     int s;//步数

     MAN(int x,int y,int s){
         this.x =x;
         this.y=y;
         this.s =s;

     }
}
public class BFS {
    int next[][] = {{0,1},{1,0},{0,-1},{-1,0}};
    int book[][] = new int[20][20];
    int flag =0;
    int tx,ty;
   public void bfs(int a[][],int x,int y,int m,int n,int p,int q){
       Queue<MAN> queue = new LinkedList<MAN>();
       MAN node = new MAN(x,y,0);
       queue.add(node);
       book[x][y] = 1;
       while(!queue.isEmpty()){
           for(int k=0;k<4;k++){
             tx = queue.peek().x+next[k][0]; 
             ty = queue.peek().y+next[k][1];
             if(tx>=m||ty>=n||tx<0||ty<0)
             {
                 continue;
             }
             if(a[tx][ty]==0&&book[tx][ty]==0)
             {
                 book[tx][ty] = 1;
                 int s =queue.element().s;
                 MAN node1 = new MAN(tx,ty,s+1);
                queue.add(node1);
             }
             if(tx==p-1&&ty==q-1)
             {
                 flag =1;
                 while(queue.size()!=1){
                       queue.remove();
                   }
                 break;
             }
           }
           if(flag ==1){

               break;
           }
           queue.poll();

       }
       int end = queue.element().s;
       System.out.println(end);


   }
    public static void main(String[] args) {
        BFS bfs = new BFS();
        int a[][]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}};
        bfs.bfs(a, 0, 0, 5, 4, 4, 3);


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值