-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumber of Provinces(BFS).cpp
More file actions
74 lines (73 loc) · 2 KB
/
Copy pathNumber of Provinces(BFS).cpp
File metadata and controls
74 lines (73 loc) · 2 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {// USING DFS
private:
void dfs(int node, vector<vector<int>>&adjLs,vector<int>&vis){
vis[node] = 1;
for(auto&x : adjLs[node]){
if(!vis[x]){
dfs(x,adjLs,vis);
}
}
}
public:
int findCircleNum(vector<vector<int>>&adj) {
int V = adj.size();
vector<vector<int>>adjLs(V);
for(int i = 0; i < V; i++){// Iterates through each city i.
for(int j = 0; j < V; j++){ // Iterates through each city j to check if it's directly connected to city i.
if(adj[i][j] == 1 and i != j) {
adjLs[i].push_back(j);
adjLs[j].push_back(i);
}
}
}
vector<int>vis(V, 0);
int cnt = 0;
for(int i = 0; i < V; i++){
if(!vis[i]){
cnt++;
dfs(i,adjLs,vis);
}
}
return cnt;
}
}; // USING BFS
class Solution {
private:
void bfs(int start, vector<vector<int>>& adjLs, vector<int>& vis) {
queue<int> q;
q.push(start);
vis[start] = 1;
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto& x : adjLs[node]) {
if (!vis[x]) {
vis[x] = 1;
q.push(x);
}
}
}
}
public:
int findCircleNum(vector<vector<int>>& adj) {
int V = adj.size();
vector<vector<int>> adjLs(V);
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (adj[i][j] == 1 && i != j) {
adjLs[i].push_back(j);
adjLs[j].push_back(i);
}
}
}
vector<int> vis(V, 0);
int cnt = 0;
for (int i = 0; i < V; i++) {
if (!vis[i]) {
cnt++;
bfs(i, adjLs, vis);
}
}
return cnt;
}
};