-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS
79 lines (66 loc) · 1.39 KB
/
DFS
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
#include <bits/stdc++.h>
using namespace std;
stack<int>s ;
void dfs(vector<vector<int>>&g,vector<int>&vis,int i)
{
s.push(i);
vis[i]=1;
while(!s.empty())
{
for(auto adj_node : g[i])
{
if(!vis[adj_node])
{
s.push(adj_node);
vis[adj_node]=1;
}
}
int node=s.top();
s.pop();
cout<<node<<" ";
}
}
void printdfs(vector<vector<int>>&g)
{
vector<int>vis(g.size(),0);
vis[0]=1;
for(int i=1;i<g.size();i++)
{
if(vis[i]==0)
{
dfs(g,vis,i);
}
}
cout<<"\n";
}
int main()
{
int node=5;
vector<vector<int>> grf2(node+1,vector<int>(0,0));
// now fill the grf2
cout << "\n\n\nNumber of nodes in graph : " << grf2.size() << endl;
grf2[1].push_back(2);
grf2[1].push_back(4);
grf2[2].push_back(1);
grf2[2].push_back(3);
grf2[3].push_back(2);
grf2[3].push_back(5);
grf2[3].push_back(4);
grf2[4].push_back(1);
grf2[4].push_back(3);
grf2[4].push_back(5);
grf2[5].push_back(3);
grf2[5].push_back(4);
// lets print our graph
for(int i=0;i<grf2.size();i++)
{
cout << i << " --> ";
for(auto e:grf2[i])
{
cout << e << " ";
}
cout << "\n";
}
printdfs(grf2);
return 0;
}