-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDFS.cpp
More file actions
171 lines (121 loc) · 2.58 KB
/
DFS.cpp
File metadata and controls
171 lines (121 loc) · 2.58 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
//**** IMPORTANT *****//
// Implementation of Graph using C++ STL
//vector < int >v [n]
//It defines an array of vectors whose index value ranges from 0 till n-1
//It means v[0] , v[1] , …. v[n-1] all are vectors.
#include<bits/stdc++.h>
#include<iomanip>
#include<cstdio>
using namespace std;
class graph {
public:
//graph(int V);
vector<int> adj[7];
int V=7;
stack<int> stak;
bool *flag= new bool[V];
void edge(int u,int v);
void printGraph();
void print();
void DFS(int s);
bool allVisited(int s);
void DFSutil(int s);
};
/*graph::graph(int V)
{
this->V = V;
adj = new list<int>[V];
} */
void graph::edge(int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void graph::printGraph()
{
for (int v = 1; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (auto x : adj[v])
cout << "-> " << x;
printf("\n");
}
}
void graph::print()
{
for (int v = 1; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (int x=0;x<adj[v].size();x++)
{
cout << "-> " << adj[v][x];
//printf("\n");
}
cout<<endl;
}
}
bool graph::allVisited(int s)
{ int count=0;
int size=adj[s].size();
for(int i=0;i<adj[s].size();i++)
{
if(flag[adj[s][i]]==false) {
count++; }
}
cout<<"source "<<s<<" Size "<<size<<" count "<<count;
if(count>0)
{ cout<<" false "<<endl; return false; }
else
{ cout<<" true "<<endl; return true; }
}
void graph::DFS(int s)
{
cout<<" Depth First Traversal of Graph "<<endl;
for(int i = 0; i < V; i++)
{ flag[i] = false; }
stak.push(s);
flag[s]=true;
cout<<s<<" ";
DFSutil(s);
}
void graph::DFSutil(int s)
{
while(!stak.empty())
{
for(int i=0;i<adj[s].size();i++)
{
if(flag[adj[s][i]]==false)
{ cout<<adj[s][i]<<" ";
flag[adj[s][i]]=true;
stak.push(adj[s][i]);
s=adj[s][i];
}
if(allVisited(s))
{ int hold=stak.top();
stak.pop();
DFSutil(hold);
}
}
}
}
int main()
{
//No of Vertcies
graph g;
//g(5);
g.edge( 1, 2);
g.edge( 1, 3);
g.edge( 2, 4);
g.edge( 2, 5);
g.edge( 3, 5);
g.edge( 4, 6);
g.edge( 4, 5);
g.edge( 5, 6);
g.printGraph();
cout<<endl;
g.DFS(1);
// cout<<a[1][2];
//g.print();
}