問題及代碼:
文件名稱:main.cpp graph.cpp graph.h
作者:鄭孚嘉
問題描述:實現圖遍歷算法,分別輸出如下圖結構的深度優先(DFS)遍歷序列和廣度優先遍歷(BFS)序列。
請利用圖算法庫
代碼:
graph.h graph.cpp請參考
1)深度遍歷
main.cpp
#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];
void DFS(ALGraph *G, int v)
{
ArcNode *p;
int w;
visited[v]=1;
printf("%d ", v);
p=G->adjlist[v].firstarc;
while (p!=NULL)
{
w=p->adjvex;
if (visited[w]==0)
DFS(G,w);
p=p->nextarc;
}
}
int main()
{
int i;
ALGraph *G;
int A[6][6]=
{
{0,1,1,1,0,0},
{1,0,1,0,1,0},
{1,1,0,0,0,1},
{1,0,0,0,0,1},
{0,1,0,0,0,1},
{0,0,1,1,1,0}
};
ArrayToList(A[0], 6, G);
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由2開始深度遍歷:");
DFS(G, 2);
printf("\n");
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由0開始深度遍歷:");
DFS(G, 0);
printf("\n");
return 0;
}
graph.h graph.cpp請參考圖算法庫
運行結果:
2)廣度遍歷
main.cpp
#include <stdio.h>
#include <malloc.h>
#include "graph.h"
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[6][6]=
{
{0,1,1,1,0,0},
{1,0,1,0,1,0},
{1,1,0,0,0,1},
{1,0,0,0,0,1},
{0,1,0,0,0,1},
{0,0,1,1,1,0}
};
ArrayToList(A[0], 6, G);
printf(" 由2開始廣度遍歷:");
BFS(G, 2);
printf(" 由0開始廣度遍歷:");
BFS(G, 0);
return 0;
}
運行結果:
知識點總結:
深度遍歷運用了遞歸算法,廣度遍歷運用了循環隊列,兩種算法都是通過對鄰接表操作實現。