-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber_of_province_Leetcode_547.cpp
145 lines (115 loc) · 3.03 KB
/
Number_of_province_Leetcode_547.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include<bits/stdc++.h>
using namespace std;
//using dfs and stack
class Solution {
public:
void DFS(vector<vector<int>>& adj, int u, vector<bool>& visited){
visited[u] = true;
for(auto &v: adj[u]){
if(!visited[v]){
DFS(adj, v, visited);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int v = isConnected.size();
vector<vector<int>> adj(v+1, vector<int> ()); //or
//vector<vector<int>> adj(v+1);
for(int i = 0; i<v; i++){
for(int j = 0; j<v; j++){
int u = isConnected[i][j];
if(u == 1){
adj[i+1].push_back(j+1);
}
}
}
vector<bool> visited(v+1, 0);
int count = 0;
for(int u = 1; u<=v; u++){
if(!visited[u]){
DFS(adj, u, visited);
count++;
}
}
return count;
}
};
//second approach
class Solution {
public:
int v;
void DFS(vector<vector<int>>& isConnected, int u, vector<bool>& visited){
visited[u] = true;
for(int j = 0; j<v; j++){
if(!visited[j] && isConnected[u][j] == 1){
DFS(isConnected, j, visited);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
v = isConnected.size();
vector<bool> visited(v, 0);
int count = 0;
for(int u = 0; u<v; u++){
if(!visited[u]){
DFS(isConnected, u, visited);
count++;
}
}
return count;
}
};
//using bfs and queue
class Solution {
public:
void BFS(vector<vector<int>>& adj, int u, vector<bool>& visited){
queue<int> que;
que.push(u);
visited[u] = true;
while(!que.empty()){
int u = que.front();
que.pop();
for(auto &v: adj[u]){
if(!visited[v]){
que.push(v);
visited[v] = true;
}
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int v = isConnected.size();
vector<vector<int>> adj(v+1, vector<int> ()); //or
//vector<vector<int>> adj(v+1);
for(int i = 0; i<v; i++){
for(int j = 0; j<v; j++){
int u = isConnected[i][j];
if(u == 1){
adj[i+1].push_back(j+1);
}
}
}
vector<bool> visited(v+1, 0);
int count = 0;
for(int u = 1; u<=v; u++){
if(!visited[u]){
BFS(adj, u, visited);
count++;
}
}
return count;
}
};
int main(){
int n;
cin>>n;
vector<vector<int>> isConnected(n, vector<int> (n));
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
cin>>isConnected[i][j];
}
}
Solution obj;
cout<<obj.findCircleNum(isConnected);
return 0;
}