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;
}

    
posted @   吴东雷  阅读(664)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示