[Geeks for Geeks] Number of Provinces

Number of Provinces

Given a graph with V vertices. Find the number of Provinces.
Note: A province is a group of directly or indirectly connected cities and no other cities outside of the group.

  • Time : O(v^2logv)
  • Space : O(v)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int uf[500];
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu] = uf[pv] = min(pu, pv);
}
public:
int numProvinces(vector<vector<int>> adj, int V) {
for(int i = 0; i < V; i++) uf[i] = i;
for(int i = 0; i < V; i++) {
for(int j = i + 1; j < V; j++) {
if(adj[i][j]) uni(i, j);
}
}
unordered_set<int> us;
for(int i = 0; i < V; i++)
us.insert(find(i));
return us.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/number-of-provinces/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.