廣度優先算法是最簡單的圖搜索算法之一,也是許多重要的圖算法的原形,從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);
}