昨天我們接好了深度優先,他是按照一直深入搜索到底,然後 展開的順序,而今天的方法廣度優先,自然是先把搜索面打開,然後再去細緻的搜索。
下面我們仔細介紹啦,其實廣度優先搜索類似於樹的層序遍歷,一層一層往下走,首先選擇一個其實頂點,然後訪問與這個頂點具有邏輯邊關係的頂點,挨個訪問,訪問完畢後,從第一個頂點開始繼續尋找它的所有邏輯邊的頂點,然後再找下一個頂點的邏輯邊頂點,就這樣一直找完所有頂點。
//廣度優先搜索 (圖->支撐樹)
//循環隊列
//順序循環隊列(定義)
typedef struct
{
int data[MAXN];
int front;
int rear;
} sqQueue;
//初始化空隊列
int InitQueue(sqQueue *Q)
{
Q->front=0;
Q->rear=0;
return true;
}
//返回隊列長度操作
int QueueLength(sqQueue Q)
{
return (Q.rear-Q.front+MAXN)%MAXN;
}
//判斷隊列是否爲空
int QueueEmpty(sqQueue Q)
{
if((Q.rear-Q.front+MAXN)%MAXN)
return true;
else
return false;
}
//增
int EnQueue(sqQueue *Q,int e)
{
if((Q->rear+1)%MAXN==Q->front)
return false;
Q->data[Q->rear]=e;
Q->data[Q->rear+1]%MAXN;
return true;
}
//刪
int DeQueue(sqQueue *Q,int *e)
{
if(Q->front==Q->rear)
return false;
*e=Q->data[Q->front];
Q->front=(Q->front+1)%MAXN;
return true;
}
//鄰接矩陣廣度遍歷算法
void BFSTraverse(MGraph G)
{
int i,j;
sqQueue Q;
InitQueue(&Q);//初始化隊列
for(i=0;i<G.numVertexes;i++)
{
if(!visited[i])
{
visited[i]=true;
cout<<G.vexs[i]<<' ';
EnQueue(&Q,i);//入隊
while(!QueueEmpty(Q))//隊列不爲空
{
DeQueue(&Q,&i);//出隊
for(j=0;j<G.numVertexes;j++)
{
if(G.arc[i][j]==1&&!visited[j])
{
visited[j]=true;
cout<<G.vexs[j]<<' ';
EnQueue(&Q,j);
}
}
}
}
}
}
//鄰接表廣度優先搜索算法
void BFSTraverse(GraphAdjList *GL)
{
int i;
EdgeNode *p;
sqQueue Q;
InitQueue (&Q);
for(i=0;i<GL->numVertexes;i++)
{
if(!visited[i])
{
visited[i]=true;
cout<<GL->adjList[i].data<<' ';
EnQueue(&Q,i);
while(!QueueEmpty(Q))
{
DeQueue(&Q,&i);
p=GL->adjList[i].firstedge;
while(!QueueEmpty(Q))
{
DeQueue(&Q,&i);
p=GL->adjList[i].firstedge;
while(p)
{
if(!visited[i])
{
visited[p->adjvex]=true;
cout<<GL->adjList[p->adjvex].data<<' ';
EnQueue(&Q,p->adjvex);
}
p=p->next;
}
}
}
}
}
}