Sicily connect components in undirected graph

时间:2023-03-09 08:35:25
Sicily connect components in undirected graph
题目介绍:

输入一个简单无向图,求出图中连通块的数目。

Input

输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。

以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。
Output

单独一行输出连通块的数目。

Sample Input
5 3
1 2
1 3
2 4
Sample Output
2

思路:

利用广度搜索,计算广度搜索的次数即为结果。

具体代码如下:

 #include <iostream>
#include <queue>
using namespace std; bool path[][];
bool visited[]; int main() {
int n, m;
cin >> n >> m; for (int i = ; i < m; i++) {
int node1, node2;
cin >> node1 >> node2;
path[node1][node2] = true;
path[node2][node1] = true;
} for (int i = ; i <= n; i++) {
visited[i] = false;
} int count = ;
int temp = n;
while (temp--) {
queue<int> store;
for (int i = ; i <= n; i++) {
if (!visited[i]) {
store.push(i);
count++;
visited[i] = true;
break;
}
} while (!store.empty()) {
for (int i = ; i <= n; i++) {
if (path[store.front()][i] && !visited[i]) {
store.push(i);
visited[i] = true;
}
}
store.pop();
}
} cout << count << endl; return ;
}