使用邻接表存图并遍历

我在写题目的时候基本上都是用邻接矩阵存图,因为方便,但有时候会发现邻接表过于浪费空间(关键是有时候直接开不了那么大的数组啊,欲哭无泪),所以我尝试了一下用邻接表,应该可以解决空间的问题。

对应的题目:https://pta.patest.cn/pta/test/1011/exam/4/question/12911


#include <iostream>

#include <string.h>

#include <malloc.h>

using namespace std;

int b[1001];///标记数组

struct node{///

   int vertex;

   struct node *next;

}grap[1001];

typedef struct node *ss;

int n,m,s;

int serch(int x,int y){///判断x,y是否直接相连通

    ss point=&grap[x];

    point=point->next;///注意

    while(point!=NULL){

        if(point->vertex==y)return 1;

        point=point->next;

    }

    return 0;

}

void dfs(int w){

   b[w]=1;

   cout<<w<<" ";

   int i;

   for(i=1;i<=n;i++){

    if(b[i]==0&&serch(w,i)){///判断条件

        dfs(i);

        if(w==s)cout<<w;

        else

        cout<<w<<" ";

    }

   }

}

void creat(int x,int y){

    ss point,pp;

    pp=(ss)malloc(sizeof(struct node));

    pp->vertex=y;

    pp->next=NULL;

    point=&grap[x];

    while(point->next!=NULL)point=point->next;

    point->next=pp;

 

    pp=(ss)malloc(sizeof(struct node));///无向图

    pp->vertex=x;

    pp->next=NULL;

    point=&grap[y];

    while(point->next!=NULL)point=point->next;

    point->next=pp;

}

 

int main()

{

    memset(b,0,sizeof(b));

    cin>>n>>m>>s;

    int p,q,i;

    for(i=1;i<=n;i++){

        grap[i].vertex=i;

        grap[i].next=NULL;

    }

    for(i=0;i<m;i++){

        cin>>p>>q;

        creat(p,q);///创表

    }

    dfs(s);

    for(i=1;i<=n;i++){

        if(b[i]==0){

            cout<<" 0"<<endl;

            break;

        }

    }

    return 0;

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值