1 6 7 0 0 3 0 4 1 4 1 5 2 3 2 4 3 5
0 3 4 2 5 1
前向星。赶脚用的有点乱 sad 水过~
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
using namespace std;
int vis[10010];
int head[10010];
int cnt;
struct node
{
int u,v;
int next;
}edge[10010];
void add(int u,int v)//加边
{
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void bfs(int s)
{
queue<int >Q;
int flag=1;//控制输出
Q.push(s);
vis[s]=1;
while(!Q.empty())
{
int u=Q.front();
Q.pop();
if(flag)
{
flag=0;
printf("%d",u);
}
else
printf(" %d",u);
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(!vis[v])
{
Q.push(v);
vis[v]=1;
}
}
}
}
int main()
{
int n,k,m,t;
int i,j,l;
int u,v;
int tt;
scanf("%d",&n);
while(n--)
{
scanf("%d %d %d",&k,&m,&t);
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
cnt=0;
for(i=0;i<m;i++)
{
scanf("%d %d",&u,&v);
add(u,v);
add(v,u);
}
for(i=0;i<m;i++)//同一个结点的同层邻接点,节点编号小的优先遍历。所以让节点小的在前面
{
for(j=head[i];j!=-1;j=edge[j].next)
for(l=edge[j].next;l!=-1;l=edge[l].next)
{
if(edge[j].v>edge[l].v)
{
tt=edge[j].v;
edge[j].v=edge[l].v;
edge[l].v=tt;
}
}
}
bfs(t);
printf("\n");
}
return 0;
}
数据结构实验之图论二:基于邻接表的广度优先搜索遍历(BFS+前向星)
原文:http://blog.csdn.net/u013486414/article/details/41416695