-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln.cpp
32 lines (30 loc) · 827 Bytes
/
soln.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
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
set<int> seen;
int cnt = 0;
for(int i = 0; i < M.size(); ++i) {
if (seen.find(i) == seen.end()) {
dfs(seen, M, i);
++cnt;
}
}
return cnt;
}
void dfs(set<int> & seen, vector<vector<int>>& M, int start) {
stack<int> stk;
stk.push(start);
seen.insert(start);
while (!stk.empty()) {
int node = stk.top();
stk.pop();
vector<int> & row = M[node];
for(int i = 0; i < row.size(); ++i) {
if (row[i] == 1 && seen.find(i) == seen.end()) {
seen.insert(i);
stk.push(i);
}
}
}
}
};