基于邻接矩阵的广度优先搜索遍历(BFS)

题目:http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2141&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 map[101][110],vis[101];
 8 int n,m,k;
 9 queue<int>q;
10 void bfs(int t)
11 {
12    int i,x,a[110],j;
13    q.push(t);
14    vis[t]=1; j=0;
15    while(!q.empty())
16    {
17        x=q.front();
18        a[++j]=x;
19        q.pop();
20        for(i=0; i<k; i++)
21        {
22            if((map[x][i]||map[i][x])&&vis[i]==0)
23            {
24                vis[i]=1;
25                q.push(i);
26            }
27        }
28    }
29    for(i=1; i<=j-1; i++)
30    printf("%d ",a[i]);
31    printf("%d
",a[i]);
32 };
33 int main()
34 {
35     int t,i,u,v;
36     scanf("%d",&n);
37     while(n--)
38     {
39         memset(map,0,sizeof(map));
40         memset(vis,0,sizeof(vis));
41         cin>>k>>m>>t;
42         for(i=0; i<m; i++)
43         {
44             cin>>u>>v;
45             map[u][v]=1;
46             map[v][u]=1;
47         }
48         bfs(t);
49     }
50 }
原文地址:https://www.cnblogs.com/bfshm/p/3163178.html