-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph-numbr-fo-islands
42 lines (40 loc) · 981 Bytes
/
graph-numbr-fo-islands
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
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int countIslands(vector<int> adj[], int n) {
vector<int> vis(n, 0);
int count = 0;
for (int i = 0; i < n; i++) {
if (vis[i] == 0) {
count++;
queue<int> q;
q.push(i);
vis[i] = 1;
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto it : adj[node]) {
if (vis[it] == 0) {
vis[it] = 1;
q.push(it);
}
}
}
}
}
return count;
}
int main() {
int n, m;
cin >> n >> m;
vector<int> adj[n];
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u - 1].push_back(v - 1); // Adjust for 0-based indexing
adj[v - 1].push_back(u - 1);
}
cout << countIslands(adj, n) << endl;
return 0;
}