5.3.1连通图的深度优先搜索
#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>
//邻接表,存储P114的5-10
#define vnum 8
//单链表定义
typedef struct arcnode
{
int adjvex; //与其相连的下个结点的编号
struct arcnode * nextarc; //指向下一个结点的指针
}ArcNodeTp;
//头结点定义
typedef struct vexnode
{
int vertex; //结点编号
ArcNodeTp * firstarc; //指向单链表的指针
}AdjList[vnum];
//对此图的定义
typedef struct graph
{
AdjList adjlist; //头结点
int vexnum; //结点数
int arcnum; //边数
}GraphTp;
//建立一个新的结点
ArcNodeTp * CreateNewNode(int adjvex)
{
ArcNodeTp * node=(ArcNodeTp *)malloc(sizeof(ArcNodeTp));
node->adjvex=adjvex;
node->nextarc=NULL;
return node;
}
//建立P114的5-10的无向图
void CreateGrapth(GraphTp & graph)
{
graph.vexnum=7;
graph.arcnum=8;
ArcNodeTp * p=NULL;
int index=0;
//建立结点
index=0;
graph.adjlist[index].vertex=index;
p=CreateNewNode(1);
//修改头结点
graph.adjlist[index].firstarc=p;
//指向下一个结点
p->nextarc=CreateNewNode(2);
index=1;
graph.adjlist[index].vertex=index;
p=CreateNewNode(3);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(4);
index=2;
graph.adjlist[index].vertex=index;
p=CreateNewNode(5);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(6);
index=3;
graph.adjlist[index].vertex=index;
p=CreateNewNode(1);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(7);
index=4;
graph.adjlist[index].vertex=index;
p=CreateNewNode(1);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(7);
index=5;
graph.adjlist[index].vertex=index;
p=CreateNewNode(2);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(6);
index=6;
graph.adjlist[index].vertex=index;
p=CreateNewNode(2);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(5);
index=7;
graph.adjlist[index].vertex=index;
p=CreateNewNode(3);
graph.adjlist[index].firstarc=p;
p->nextarc=CreateNewNode(4);
}
//深度优先算法
void Dfs(GraphTp graph,int value,int visited[])
{
ArcNodeTp *p=NULL;
cout<<"访问顶点"<<value<<endl;
visited[value]=1;
p=graph.adjlist[value].firstarc;
while(p!=NULL)
{
if (!visited[p->adjvex])
{
Dfs(graph,p->adjvex,visited);
}
p=p->nextarc;
}
}
int main(int argc, char* argv[])
{
int visited[vnum];
for(int i=0;i<vnum;i++)
{
visited[i]=0;
}
GraphTp graph;
CreateGrapth(graph);
Dfs(graph,0,visited);
return 0;
}
一点说明:为什么在标题中要嵌入英文?原因是为了能够让国外的网友能查询到这篇文章。平常在Google上查资料的时候,经常参考国外网友的博客,帮助我解决了很多问题,所以我也想让他们能够参考我写的内容。当然文中我不可能全部译为英文,所以我尽量把代码粘全,靠代码说话吧。



浙公网安备 33010602011771号