BFS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <queue>
using namespace std;
void bfs(int);
bool used[110];
int a[110][110], n;
int main() {
int cnt=0;
cin>>n;
for (int i=1; i<=n; ++i)
for (int j=1; j<=n; ++j) cin>>a[i][j];
for (int j=1; j<=n; ++j)
if (!used[j]){
++cnt;
bfs(j);
}
}
void bfs(int x){
int u;
used[x]=true;
queue<int>q;
q.push(x);
while (!q.empty()){
u=q.front();
q.pop();
cout<<u<<" ";
for (int i=1; i<=n; ++i){
if ((a[u][i]==1)&&(!used[i])){
q.push(i);
used[i]=true;
}
}
}
}