-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathAnswer57.cpp
43 lines (35 loc) · 1.03 KB
/
Answer57.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
#include<unordered_map>
#include<list>
void dfs(int node, unordered_map <int, list<int> > & adj, unordered_map<int,bool> & visited, vector<int> & component){
component.push_back(node);
visited[node] = true;
for(auto i:adj[node]){
if( !visited[i] ){
dfs(i,adj,visited,component);
}
}
}
vector<vector<int>> depthFirstSearch(int V, int E, vector<vector<int>> &edges)
{
// prepare of adjacent list
unordered_map <int, list<int> > adj;
for (int i=0; i < edges.size(); i++)
{
int u = edges[i][0];
int v = edges[i][1];
adj[u].push_back(v);
adj[v].push_back(u);
}
//ans
vector<vector<int>> ans;
//visited having i th node and bool
unordered_map <int,bool > visited;
for(int i=0;i<V;i++){
if(!visited[i]){
vector<int>component;
dfs(i,adj,visited ,component);
ans.push_back(component);
}
}
return ans;
};