邻接表存储图利用BFS遍历

7 篇文章 0 订阅
5 篇文章 0 订阅
//今天上机写的邻接表存储图利用BFS遍历:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
struct node//存节点所连接的点
{
    int id;
    node *next;
};
struct list//存各个节点的顶点值
{
    int data;
    node *first;
}AdjList[1000];
struct ALGraph
{
    int v,n;//v顶点数,边数
}ALGraph;
int vis[1000];//访问标记 
void create_list(node *&head,int n)
{
    node *p=head;
    for(int i=0;i<n;++i)
    {
        node *pnew=new node;
        scanf("%d",&pnew->id);
        pnew->next=NULL;
        p->next=pnew;
        p=p->next;
    }
    p->next=NULL;
    p=head->next;
    while(p)
    {
        printf("%d ",p->id);
        p=p->next;
    }
    putchar('\n');
}
void createAdjList()
{
    printf("请输入领接表的顶点和弧数:");
    scanf("%d%d",&ALGraph.v,&ALGraph.n);
    for(int i=1;i<=ALGraph.v;++i)
    {
        printf("请输入第%d个顶点值\n",i);
        scanf("%d",&AdjList[i].data);
        printf("请输入该点所相邻点的个数:");
        int n;
        scanf("%d",&n);
        printf("如果相邻点存在请输入各个顶点,不存在请输入下个顶点信息\n");
        node *head=new node;
        if(n>0)
        {
            create_list(head,n);
            AdjList[i].first=head->next;//第一个为空
        }
        else
        AdjList[i].first=NULL;
    }
}
void BFS()
{
    printf("%d ",AdjList[1].data);
    for(int i=1;i<=ALGraph.v;++i)
    {
        while(AdjList[i].first&&!vis[i])
        {
            printf("%d ",AdjList[i].first->id);
            AdjList[i].first=AdjList[i].first->next;
            vis[i]=1;
        }
    }
    /*for(int i=1;i<=ALGraph.v;++i)
    {
    	cout<<AdjList[i].data<<" ";
        while(AdjList[i].first)
        {
            printf("%d ",AdjList[i].first->id);
            AdjList[i].first=AdjList[i].first->next;
        }putchar('\n');
	}*/
	putchar('\n');
}
int main()
{
    memset(vis,0,sizeof(vis));
    int x;
    createAdjList();
    BFS();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值