基于邻接表的广度优先搜索遍历(bfs)

题目:http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2142&cid=1186

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #include<iostream>
 5 #include<queue>
 6 using namespace std;
 7 int vis[101];
 8 int n,m,k;
 9 queue<int>q;
10 struct node
11 {
12     int u,v;
13     struct node *next;
14 }*head[110];
15 void add(int u, int v)
16 {
17    struct node *p = (struct node*)malloc(sizeof(struct node));
18    p->u = u;
19    p->v = v;
20    p->next = head[u];
21    head[u] = p;
22 };
23 int cmp(const void *a,const void *b)
24 {
25     return *(int *)a-*(int *)b;
26 }
27 void bfs(int t)
28 {
29    int i,x,a[110],j,b[110],y;
30    q.push(t);
31    vis[t]=1; j=0;
32    while(!q.empty())
33    {
34        x=q.front();
35        a[++j]=x;
36        q.pop();
37        y=0;
38            for(struct node *p=head[x]; p!=NULL; p=p->next)
39            {
40                if(vis[p->v]==0)
41                {
42                    b[y++]=p->v;
43                    vis[p->v]=1;
44                }
45            }
46         if(y>=1)
47         qsort(b,y,sizeof(b[0]),cmp);
48         for(i=0; i<=y-1; i++)
49         q.push(b[i]);
50    }
51    for(i=1; i<=j-1; i++)
52    printf("%d ",a[i]);
53    printf("%d
",a[i]);
54 };
55 int main()
56 {
57     int t,i,u,v;
58     scanf("%d",&n);
59     while(n--)
60     {
61         memset(head,NULL,sizeof(head));
62         memset(vis,0,sizeof(vis));
63         cin>>k>>m>>t;
64         for(i=0; i<m; i++)
65         {
66             cin>>u>>v;
67             add(u,v);
68             add(v,u);
69         }
70         bfs(t);
71     }
72 }
原文地址:https://www.cnblogs.com/bfshm/p/3163170.html