bfs 邻接表(需要优化 可能会RE *【模板】)

时间:2022-03-16 16:46:14
//---基于邻接表的bfs


#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <queue> using namespace std; struct node
{
int date;
struct node *next;
}*head[101], *tail[101]; void bfs(int s)
{
int flag=0; //标记输出,保证输出格式的正确的 bool vis[101];
memset(vis, false, sizeof(vis) );
queue<int>q; vis[s]=true; //标记起点访问
q.push(s);
int cur; struct node *p;
while( !q.empty() )
{
cur=q.front();
if(flag==0)
{
printf("%d", cur );
flag=1;
}
else if(flag==1)
{
printf(" %d", cur );
} q.pop();
if( head[cur] ) //如果不空
{
//开始遍历
p=head[cur]->next;
while(p)
{
if(vis[p->date]==false)
{
q.push(p->date);
vis[p->date]=true;
}
p=p->next;
}
}
}
printf("\n");
} int main()
{
int t;
cin>>t;
int n, m, s;
int u, v;
int i; while(t--)
{
for(i=0; i<=100; i++)
{
head[i]=new struct node;
head[i]->next = NULL;
tail[i] = head[i];
}
//邻接表的初始化 scanf("%d %d %d", &n, &m, &s) ;
struct node *p, *q;
for(i=0; i<m; i++)
{
scanf("%d %d", &u, &v );
p=new struct node;
p->date=v; p->next=NULL;
q=new struct node;
q->date=u; q->next=NULL; tail[u]->next=p; tail[u]=p;
tail[v]->next=q; tail[v]=q;
} //建立邻接表
bfs(s);
}
return 0;
}