图的顺序表存储

来源:互联网 发布:便笺软件 编辑:程序博客网 时间:2024/05/17 23:14

输入图的点数和边数(图顶点的标号在0开始);

然后输入图的边;

然后输入一个数字,代表在这个点开始进行遍历

#include <stdio.h>#include <string.h>#include <stdlib.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;裁判实现,细节不表 */{    MGraph M =  (GNode*) malloc(sizeof(GNode));    memset(Visited, false, sizeof(Visited));    int n, e;    scanf("%d %d", &n, &e);    M->Nv = n; M->Ne = e;    for(int i = 0; i < (M->Ne); i++)    {        int v1, v2;        scanf("%d %d", &v1, &v2);        (*M).G[v1][v2] = (*M).G[v2][v1] = 1;    }    return M;}void Visit( Vertex V ){    printf(" %d", V);}void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ){    Visited[V] = true;    Visit(V);    for(int i = 0; i <= Graph->Nv; i++)    {        if((*Graph).G[i][V] == 1 && !Visited[i])        {            DFS(Graph, i, Visit);        }    }}int main(){    MGraph G;    Vertex V;    G = CreateGraph();   scanf("%d", &V);    printf("DFS from %d:", V);    DFS(G, V, Visit);    return 0;}


原创粉丝点击