第十二週專案3 - 圖遍歷演算法實現(2)
/*Copyright (c) 2015, 煙臺大學計算機與控制工程學院
* All rights reserved.
* 檔名稱:H1.cpp
* 作者:辛志勐
* 完成日期:2015年11月23日
* 版本號:VC6.0
* 問題描述:廣度優先遍歷——BFS
* 輸入描述:無
* 程式輸出:圖的基本輸出
*/
#include <stdio.h>
#include <malloc.h>
#define MAXV 100 //最大頂點個數
#define INF 32767 //INF表示∞
typedef int InfoType;
//以下定義鄰接矩陣型別
typedef struct
{
int no; //頂點編號
InfoType info; //頂點其他資訊,在此存放帶權圖權值
} VertexType; //頂點型別
typedef struct //圖的定義
{
int edges[MAXV][MAXV]; //鄰接矩陣
int n,e; //頂點數,弧數
VertexType vexs[MAXV]; //存放頂點資訊
} MGraph; //圖的鄰接矩陣型別
//以下定義鄰接表型別
typedef struct ANode //弧的結點結構型別
{
int adjvex; //該弧的終點位置
struct ANode *nextarc; //指向下一條弧的指標
InfoType info; //該弧的相關資訊,這裡用於存放權值
} ArcNode;
typedef int Vertex;
typedef struct Vnode //鄰接表頭結點的型別
{
Vertex data; //頂點資訊
int count; //存放頂點入度,只在拓撲排序中用
ArcNode *firstarc; //指向第一條弧
} VNode;
typedef VNode AdjList[MAXV]; //AdjList是鄰接表型別
typedef struct
{
AdjList adjlist; //鄰接表
int n,e; //圖中頂點數n和邊數e
} ALGraph; //圖的鄰接表型別
void ArrayToList(int *Arr, int n, ALGraph *&); //用普通陣列構造圖的鄰接表
void DispAdj(ALGraph *G);//輸出鄰接表G
void ArrayToList(int *Arr, int n, ALGraph *&G)
{
int i,j,count=0; //count用於統計邊數,即矩陣中非0元素個數
ArcNode *p;
G=(ALGraph *)malloc(sizeof(ALGraph));
G->n=n;
for (i=0; i<n; i++) //給鄰接表中所有頭節點的指標域置初值
G->adjlist[i].firstarc=NULL;
for (i=0; i<n; i++) //檢查鄰接矩陣中每個元素
for (j=n-1; j>=0; j--)
if (Arr[i*n+j]!=0) //存在一條邊,將Arr看作n×n的二維陣列,Arr[i*n+j]即是Arr[i][j]
{
p=(ArcNode *)malloc(sizeof(ArcNode)); //建立一個節點*p
p->adjvex=j;
p->info=Arr[i*n+j];
p->nextarc=G->adjlist[i].firstarc; //採用頭插法插入*p
G->adjlist[i].firstarc=p;
}
G->e=count;
}
void DispAdj(ALGraph *G)
//輸出鄰接表G
{
int i;
ArcNode *p;
for (i=0; i<G->n; i++)
{
p=G->adjlist[i].firstarc;
printf("%3d: ",i);
while (p!=NULL)
{
printf("-->%d/%d ",p->adjvex,p->info);
p=p->nextarc;
}
printf("\n");
}
}
void BFS(ALGraph *G, int v)
{
ArcNode *p;
int w,i;
int queue[MAXV],front=0,rear=0; //定義迴圈佇列
int visited[MAXV]; //定義存放節點的訪問標誌的陣列
for (i=0; i<G->n; i++) visited[i]=0; //訪問標誌陣列初始化
printf("%2d",v); //輸出被訪問頂點的編號
visited[v]=1; //置已訪問標記
rear=(rear+1)%MAXV;
queue[rear]=v; //v進隊
while (front!=rear) //若佇列不空時迴圈
{
front=(front+1)%MAXV;
w=queue[front]; //出隊並賦給w
p=G->adjlist[w].firstarc; //找w的第一個的鄰接點
while (p!=NULL)
{
if (visited[p->adjvex]==0)
{
printf("%2d",p->adjvex); //訪問之
visited[p->adjvex]=1;
rear=(rear+1)%MAXV; //該頂點進隊
queue[rear]=p->adjvex;
}
p=p->nextarc; //找下一個鄰接頂點
}
}
printf("\n");
}
int main()
{
ALGraph *G;
int A[5][5]=
{
{0,1,0,1,0},
{1,0,1,0,0},
{0,1,0,1,1},
{1,0,1,0,1},
{0,0,1,1,0}
};
ArrayToList(A[0], 5, G);
printf(" 由2開始廣度遍歷:");
BFS(G, 2);
printf(" 由0開始廣度遍歷:");
BFS(G, 0);
return 0;
}
知識點總結:定義迴圈佇列,實現廣度遍歷。
學習新得:剛一看到隊,腦子一片空白,趕緊往前翻了翻書看了一遍,也算是複習了吧。