-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path547 friend circles
51 lines (50 loc) · 1.35 KB
/
547 friend circles
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
dfs:
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
vector<bool>visited(M.size(),false);
int count=0;
for(int i=0;i<M.size();i++){
if(!visited[i]){
dfs(i,M,visited);
count++;
}
}
return count;
}
void dfs(int x,vector<vector<int>>&M,vector<bool>&visited){
visited[x]=true;
for(int i=0;i<M[x].size();i++){
if(M[x][i]==1&&!visited[i]){
dfs(i,M,visited);
}
}
}
};
====================================================================================================================================
bfs:
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
vector<bool>visited(M.size(),false);
int cnt=0;
queue<int>q;
for(int i=0;i<M.size();i++){
if(!visited[i]){
q.push(i);
while(q.size()){
int x=q.front();
q.pop();
visited[x]=true;
for(int j=0;j<M[x].size();j++){
if(M[x][j]==1&&!visited[j]){
q.push(j);
}
}
}
cnt++;
}
}
return cnt;
}
};