邻接表建图+深度遍历+判断连通性

来源:互联网 发布:java程序员考证 编辑:程序博客网 时间:2024/06/06 03:59
#include<stdio.h>#include<stdlib.h>#define Max 10typedef struct Node{    int ver;    struct Node*next;}VexNode;struct Adj{    VexNode*next;}; Adj adj[Max];int visit[Max];void depth(int start){    printf("%d ",start);    visit[start]=1;     VexNode *p;    p=adj[start].next;    while(p!=NULL)    {        int v=p->ver;        if(!visit[v])            depth(v);        p=p->next;    }}void InitMap(Adj adj[],int numN){    for(int i=1;i<=numN;i++)    adj[i].next=NULL;}void CreatMap(Adj adj[],int numB){    for(int i=0;i<numB;i++){        int a,b;        scanf("%d%d",&a,&b);        VexNode*q;        q=(VexNode*)malloc(sizeof(VexNode));        q->ver=b;        q->next=adj[a].next;        adj[a].next=q;        VexNode*q1;        q1=(VexNode*)malloc(sizeof(VexNode));        q1->ver=a;        q1->next=adj[b].next;        adj[b].next=q1;    }}  int iscon(Adj adj[],int numN){    for(int i=1;i<=numN;i++)    if(!visit[i])    return 0;    return 1;} int main()    {    int numN,numB;    scanf("%d%d",&numN,&numB);    InitMap(adj,numN);    CreatMap(adj,numB);    depth(1);   //1为开始遍历的点     printf("%s\n",iscon(adj,numN)==1?"是连通图":"不是联通图!");    return 0;}
0 0
原创粉丝点击