-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS-in-graph.cpp
43 lines (34 loc) · 1009 Bytes
/
DFS-in-graph.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
void dfs(int node, unordered_map<int, bool> &visited, unordered_map<int, list<int>> &adj, vector<int> &component){
//ans store
component.push_back(node);
//mark visited
visited[node] = true;
//har connected node ke liye recursive call
for(auto i : adj[node]){
if(!visited[i]){
dfs(i, visited, adj, component);
}
}
}
vector<vector<int>> depthFirstSearch(int V, int E, vector<vector<int>> &edges)
{
//prepare adjList
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);
}
vector<vector<int>> ans;
unordered_map<int, bool> visited;
//for all nodes call DFS, if not visited
for(int i=0; i<V; i++){
if(!visited[i]){
vector<int> component;
dfs(i, visited, adj, component);
ans.push_back(component);
}
}
return ans;
}