#include<iostream>
using namespace std;
#include<queue>
typedef int vertype ;
#define max 100
int book[max];
struct ArcNode
{
int adjvex;//记录一条边的右顶点的下标
int weight;
ArcNode *next;//下一条边
};
struct VNode
{
vertype data;//顶点的类型
ArcNode *firstarc;//顶点的第一条边,是连接顶点数组与单链表的桥梁
};
struct Graph
{
int vernum;//图顶点的总个数
int arcnum;//图边的总个数
VNode ver[max];//顶点数组
};
int change(Graph *G,vertype v)
{
for(int i=1;i<=G->vernum;i++)
{
if(G->ver[i].data==v)
return i;
}
}
void creat(Graph *G)
{
cout<<"输入图的顶点数和边数"<<endl;
cin>>G->vernum>>G->arcnum ;
cout<<"输入"<<G->vernum<<"个顶点的信息"<<endl;
for(int i=1;i<=G->vernum;i++)
{
cin>>G->ver[i].data;
G->ver[i].firstarc=NULL;//初始化顶点数组和边
book[i]=0;
}
cout<<"输入"<<G->arcnum<<"个边的信息(v1,v2,weight)"<<endl;
for(int i=1;i<=G->arcnum;i++)
{
int v1,v2,weight;
int t1,t2;
cin>>t1>>t2>>weight;
v1=change(G,t1);
v2=change(G,t2);
ArcNode *node=new ArcNode;
node->adjvex=v2;//一条边的右端点
node->next=NULL;//新创建的结点初始化
node->weight=weight;
/*ArcNode *tnode=new ArcNode;
tnode->adjvex=v1;
tnode->next =NULL;
tnode->weight=weight; //这段代码加上就是无向图了
tnode->next=G->ver[v2].firstarc;
G->ver[v2].firstarc=tnode;
*/
node->next=G->ver[v1].firstarc; //这里是头插法
G->ver[v1].firstarc=node;
/*ArcNode *p=G->ver[v1].firstarc;//特别注意这里是v1的第一条边,
//v2是插入v1的第一条边或者是v1的next条边
if(p==NULL)
G->ver[v1].firstarc=node;//这里也是v1
else
{
while(p->next) / /尾插法
{
p=p->next;
}
p->next=node;
}
*/
}
}
void BFS(Graph *G)
{
cout<<endl;
queue<int>q;
for(int i=1;i<=G->vernum;i++)
{ book[i]=0;} //标记初始化
for(int i=1;i<=G->vernum;i++)
{
if(book[i]==0)
q.push(i);
while(!q.empty())
{
int t=q.front();
q.pop();
book[t]=1;
cout<<G->ver[t].data<<" "; //出队输出
ArcNode *p=G->ver[t].firstarc;//找i第一条边
while(p) //找i其他的边(广度)
{
if(book[p->adjvex]==0)
{
book[p->adjvex]=1;
q.push(p->adjvex);//将邻边标记入队
}
p=p->next;
}
}
}
}
图邻接表BFS
猜你喜欢
转载自blog.csdn.net/m0_53389337/article/details/121434738
今日推荐
周排行