Repository navigation
Expand file tree
/
Copy pathGraph_dfs.cpp
More file actions
91 lines (75 loc) · 1.49 KB
/
Copy pathGraph_dfs.cpp
File metadata and controls
91 lines (75 loc) · 1.49 KB
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
#include <iostream>
#include <unordered_map>
#include <list>
#include <vector>
#include <queue>
using namespace std;
unordered_map<int, list<int>> adj;
unordered_map<int, bool> visited;
vector<int> ans;
// create a adj list
void addEdge(int u, int v, bool direction)
{
// creation a edge from u to v
adj[u].push_back(v);
if (direction == 0)
{
adj[v].push_back(u);
}
}
// dfs function
void dfs(int node)
{
// mark as visited
visited[node] = true;
ans.push_back(node);
// cout << node << " ";
// Recursive call for each connected node(means neighbours)
for (auto neighbour : adj[node])
{
if (!visited[neighbour])
{
dfs(neighbour);
}
}
}
int main()
{
int n;
cout << "Enter a number of Nodes :" << endl;
cin >> n;
int m;
cout << "Enter a number of Edges :" << endl;
cin >> m;
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
// prepare the adj list
addEdge(u, v, 0);
}
// input :
// Enter a number of Nodes :
// 4
// Enter a number of Edges :
// 6
// 0 1
// 0 2
// 1 2
// 2 0
// 2 3
// 3 3
// for (int i = 0; i < n; i++)
// {
// if (!visited[i])
// {
// dfs(i);
// }
// }
dfs(2);
for (auto i : ans)
{
cout << i << " ";
}
return 0;
}