邻接矩阵存储图的深度优先遍历

题目要求:
试实现邻接矩阵存储图的深度优先遍历。


函数接口定义:

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );

其中MGraph是邻接矩阵存储的图,定义如下:

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;  /* 顶点数 */
    int Ne;  /* 边数   */
    WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */

函数DFS应从第V个顶点出发递归地深度优先遍历图Graph,遍历时用裁判定义的函数Visit访问每个顶点。当访问邻接点时,要求按序号递增的顺序。题目保证V是图中的合法顶点。


裁判测试程序样例:

#include <stdio.h>

typedef enum {false, true} bool;
#define MaxVertexNum 10  /* 最大顶点数设为10 */
#define INFINITY 65535   /* ∞设为双字节无符号整数的最大值65535*/
typedef int Vertex;      /* 用顶点下标表示顶点,为整型 */
typedef int WeightType;  /* 边的权值设为整型 */

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;  /* 顶点数 */
    int Ne;  /* 边数   */
    WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
bool Visited[MaxVertexNum]; /* 顶点的访问标记 */

MGraph CreateGraph(); /* 创建图并且将Visited初始化为false;裁判实现,细节不表 */

void Visit( Vertex V )
{
    printf(" %d", V);
}

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );


int main()
{
    MGraph G;
    Vertex V;

    G = CreateGraph();
    scanf("%d", &V);
    printf("DFS from %d:", V);
    DFS(G, V, Visit);

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:给定图如下
这里写图片描述
5

输出样例:
DFS from 5: 5 1 3 0 2 4 6

Code:

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) )
/*第一个参数是传入二维数组的头地址(即图)
第二个参数是结点编号
第三个参数是传入Visit()这个函数的地址(可以自行百度函数是怎么作为参数传递的)*/
{
    /*从第V个顶点出发递归地深度优先遍历图G*/
    int i;
    Visited[V] = true;//标记为true,说明已经遍历过了
    Visit(V); //打印出V这个结点
    for(i = 0; i < Graph->Nv; i++) //遍历V的每个邻接点
    {
        if(Graph->G[V][i] == 1 && !Visited[i])
        /*Graph->G[V][i] == 1说明有结点,!Visited[i]为真,说明未遍历过*/
        {
           DFS(Graph, i, Visit); //递归调用DFS
        }
    }
}

这里给出裁判实现的代码:
(可以把这段代码放到本地去运行):

#include<stdlib.h> //需要增加此头文件

MGraph CreateGraph() //创建图并且将Visited初始化为false
{
    int Nv, i, VertexNum;
    int v1, v2;
    Vertex V, W ;
    MGraph Graph;
    printf("请输入顶点个数:\n");
    scanf("%d", &VertexNum);
    Graph = (MGraph)malloc(sizeof(struct GNode));
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    for(V = 0; V < Graph->Nv; V ++) {
        for(W = 0; W < Graph->Nv; W ++) {
            Graph->G[V][W ] = INFINITY;
        }
    }
    printf("请输入边数:\n");
    scanf("%d", &Graph->Ne);
    if(Graph->Ne) {
        for(i = 0; i < Graph->Ne; i ++) {
            scanf("%d %d", &v1, &v2);
            Graph->G[v1][v2] = 1;
            Graph->G[v2][v1] = 1;
        }
    }

    return Graph;
}

案例的输入方式(其中最后输入的5的代表从5这个结点开始进行深度优先遍历):
这里写图片描述

附:邻接表存储图的广度优先遍历链接
点击跳转

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值