(算法入门)基本图论-广度优先搜索之JAVA实现

广度优先算法是最简单的图搜索算法之一,也是许多重要的图算法的原形,从PRIM到Dijkstra都使用了类似于广度优先算法的思想。

其思想如下:

已知图G=(V,E)和一个源顶点s,广度优先搜索以一种系统的方式探寻G的边,从而“发现”S所能到达的所有顶点,并计算s到所有这些顶点的距离(最少边数),该算法同时能生成一棵根为S且包括所有可达顶点的宽度优先树。对从S可达的任意顶点V,宽度优先树中从S到V的路径对应于图G中从S到V的最短路径,即包含最小边数的路径。该算法对有向图和无向图同样适用。

广度优先思想是一个队列的思想,需要使用者在使用的过程中构建一个单队列。

具体设计:

1. 数据结构

图的数据结构请参考我的另一篇博文,里面有详细的构造方法。

在这里面,我自己构建了一个队列,是模仿以前数据结构的原理做出来的,略繁琐。大家也可以直接使用LinkedList 构建,几行代码的事。

public class QNode {
  public   int data;
  public   QNode next=null;
}

public class Queue {
	public   QNode front=null;
	public   QNode rear=null;
}
public class QueueFunction {
	
     public Queue CreateQueue(){
    	 Queue Queue=new Queue();
    	 QNode QNode=new QNode();
    	 Queue.front=Queue.rear=QNode;
    	 QNode.next=null;
    	 return Queue;
     }
     
     public void EnQueue(Queue Queue,int data){
    	 QNode QNode=new QNode();
    	 QNode.data=data;
    	 if(Queue.front==Queue.rear){
    	 Queue.front=QNode;
    	 Queue.front.next=Queue.rear;
    	 }
    	 QNode p=Queue.front;
    	 while(p.next!=Queue.rear){
    		 p=p.next;
    	 }
    	 p.next=QNode;
    	 p.next.next=Queue.rear;
     }
     public int DeQueue(Queue Queue){
    	 int p=-1;
    	 if(Queue.front==Queue.rear)  ; 
    	 else{
    		 p=Queue.front.data;
    		 Queue.front=Queue.front.next;
    		 
    	 }
    	 return p;
     }
     
}



2.BFS

public void BFS(Queue Queue , Graph G ,int v){
	 if(visited[v]==false){
	 visited[v]=true;
	 System.out.println(G.arrVnode[v].data);System.out.print("    ");
	 ArcNode node =G.arrVnode[v].nextarc;
	 while(node!=null){
		 if(visited[node.adjvex]==false&&queueed[node.adjvex]==false){
			 QueueFunction.EnQueue(Queue, node.adjvex);
			 queueed[node.adjvex]=true;
		 }
		 node=node.nextarc;
	 }
	 BFS(Queue,G,QueueFunction.DeQueue(Queue));
	 
 }
 }

3.主函数

public  static void main(String[] args){
	   int[] a=new int[10000];
	   int[] b=new int[10000];
	   int[] c=new int[10000];
	   int[] shortest=new int[10000];
	   In in = new In(args[0]);
	   int vexnum=in.readInt();
	   int arcnum=in.readInt();
	   for(int arc=1;arc<=arcnum;arc++){
		   a[arc]=in.readInt();
		   b[arc]=in.readInt();
		   c[arc]=in.readInt();
	   }
	   for(int arc=1;arc<=arcnum;arc++){
		   shortest[arc]=10000;
	   }
	   GrahpFunction GrahpFuntion=new GrahpFunction();
	   Queue Queue=new Queue();
	   Graph G=GrahpFuntion.CreateGrahp(vexnum,arcnum,a,b,c);
	   Toposort top=new Toposort();
	   top.Toposortmethod(G);
   System.out.println("BFS结果为:");
   GrahpFuntion.BFS(Queue, G, 1);
	   }






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值