資料結構學習筆記(四) 圖之鄰接表實現深度優先遍歷
阿新 • • 發佈:2019-01-25
一下是使用鄰接表儲存表示,實現圖的深度優先遍歷的示例。
用於遍歷的有向圖如下:
#include<iostream>
#define MaxVertexNum 6
using namespace std;
//抽象資料型別
typedef char vertextype;
//邊結點型別
typedef struct edge
{
int mark;
int no;
struct edge *next;
}edgetype;
//點結點型別
typedef struct
{
int mark;
vertextype vertex;
edgetype *firstArc;
}vertexNode;
//圖
typedef struct
{
vertexNode vex[MaxVertexNum];
int n,e;
}ALGraph;
ALGraph G;
edgetype *p;//用於遍歷邊結點
//構造有向圖出邊表
void create()
{
G.n=6;
G.vex[0].vertex='a';
G.vex[1].vertex='b';
G.vex[2].vertex='c';
G.vex[3].vertex='d';
G.vex[4].vertex='e';
G.vex[5].vertex ='f';
G.vex[0].mark=G.vex[1].mark=G.vex[2].mark=G.vex[3].mark=G.vex[4].mark=G.vex[5].mark=0;
edgetype *e1=new edgetype;
edgetype *e2=new edgetype;
edgetype *e3=new edgetype;
edgetype *e4=new edgetype;
edgetype *e5=new edgetype;
edgetype *e6=new edgetype;
edgetype *e7=new edgetype;
edgetype *e8=new edgetype;
edgetype *e9=new edgetype;
edgetype *e10=new edgetype;
e1->mark=e2->mark=e3->mark=e4->mark=e5->mark=0;
e6->mark=e7->mark=e8->mark=e9->mark=e10->mark=0;
e1->no=1;
e2->no=4;
e3->no=5;
e4->no=5;
e5->no=1;
e6->no=2;
e7->no=3;
e8->no=5;
e9->no=2;
e10->no=3;
G.vex[0].firstArc=e1;
e1->next=e2;
e2->next=e3;
e3->next=NULL;
G.vex[1].firstArc=e4;
e4->next=NULL;
G.vex[2].firstArc=e5;
e5->next=NULL;
G.vex[3].firstArc=e6;
e6->next=NULL;
G.vex[4].firstArc=e7;
e7->next=e8;
e8->next=NULL;
G.vex[5].firstArc=e9;
e9->next=e10;
e10->next=NULL;
}
//圖的深度優先遍歷
void DFS(ALGraph &G,int i)
{
edgetype *p;
G.vex[i].mark=1;
//cout<<G.vex[i].vertex;
p=G.vex[i].firstArc;
while(p!=NULL)
{
if(G.vex[p->no].mark==0)
{
p->mark=1;
cout<<'('<<G.vex[i].vertex<<','<<G.vex[p->no].vertex<<')';
DFS(G,p->no);
}
p=p->next;
}
}
//深度優先遍歷圖的演算法
void DFS_Component(ALGraph &G)
{
int i;
for(i=0;i<G.n;i++)
if(G.vex[i].mark==0)
DFS(G,i);
cout<<endl;
}
//測試函式
int main()
{
create();
DFS_Component(G);
return 0;
}