邻接矩阵形式图的深度优先搜索

/** 测试用例数据结构 陈越 第二版 P219 6.2
 * 8
 * 9
* 0 1 1 
* 1 2 1 
* 2 3 1 
* 3 0 1 
* 0 4 1 
* 4 5 1 
* 5 6 1 
* 6 7 1 
* 7 4 1 
 * A B C D E F G H
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MaxVertexNum 100
#define INFINITY 65535

typedef int Vertex;      /**< 用顶点下标表示顶点,一般用两个vertex表示一个顶点 */
typedef int WeightType;
typedef char DataType;

/**< 图结点的定义 */
typedef struct GNode * PtrToGNode;
struct GNode
{
    int Nv;
    int Ne;
    WeightType G[MaxVertexNum][MaxVertexNum];
    DataType Data[MaxVertexNum];
};
typedef PtrToGNode MGraph;

/**< 边的定义 */
typedef struct ENode * PtrToENode;
struct ENode
{
    Vertex v1, v2;
    WeightType Weight;
};
typedef PtrToENode Edge;

bool visited[MaxVertexNum];/**< 是否已经访问的标记 */

/**< 初始化一个有VertexNum个顶点,边数为0的图 */
MGraph CreatGraph(int VertexNum);
MGraph CreatGraph(int VertexNum)
{
    Vertex i, j;
    MGraph Graph;

    Graph = (MGraph)malloc(sizeof(struct GNode));
    Graph->Nv = VertexNum;
    Graph->Ne = 0;
    for(i=0; i<VertexNum; i++)
    {
        visited[i] = false; /**< 把访问标记默认设置为false */
        for(j=0; j<VertexNum; j++)
        {
            Graph->G[i][j] = INFINITY;
        }
    }

    return Graph;
}

void InsertEdge(MGraph Graph, Edge E);
void InsertEdge(MGraph Graph, Edge E)
{
    Graph->G[E->v1][E->v2] = E->Weight;
    /**< 无向图需要插入逆方向的权重值,若是有向图则无须以下语句 */
    Graph->G[E->v2][E->v1] = E->Weight;
}

/**< 这里的build其实就是平时main里面做的东西 */
MGraph BuildGraph();
MGraph BuildGraph()
{
    MGraph Graph;
    Edge E;
    Vertex V;
    int Nv, i;

    scanf("%d", &Nv); /**< 读入顶点个数 */

    Graph = CreatGraph(Nv);

    scanf("%d", &(Graph->Ne));

    {
        printf("Number of Edge:%d\n", Graph->Ne);
    }

    if(Graph->Ne>0)
    {
        E = (Edge)malloc(sizeof(struct ENode));
        for(i=0 ;i<Graph->Ne; i++)
        {
            scanf("%d %d %d", &E->v1, &E->v2, &E->Weight);
            InsertEdge(Graph, E);
        }
    }
    /**< 若然还有数据 */
    char ch;
    for(i=0; i<Graph->Nv; i++)
    {
        while((ch=getchar())==' '||ch=='\n'){};
        Graph->Data[i] = ch;
        visited[i] = false;
    }

    return Graph;
}

void DFSprint(MGraph Graph, Vertex i);
void DFSprint(MGraph Graph, Vertex i)
{
    printf("%c\t", Graph->Data[i]);
}

void DFS(MGraph Graph, Vertex i);
void DFS(MGraph Graph, Vertex i)
{
    visited[i] = true;
    DFSprint(Graph, i);
    int j;
    for(j=0; j<Graph->Nv; j++)
    {
        if(Graph->G[i][j]!=INFINITY && !visited[j])
        {
            DFS(Graph, j);
        }
    }

}

int main()
{
    int i;
    MGraph g;
    g = BuildGraph();
    DFS(g, 4);
    system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值