//今天上机写的邻接表存储图利用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;
}
邻接表存储图利用BFS遍历
最新推荐文章于 2022-03-19 14:54:18 发布