-
Notifications
You must be signed in to change notification settings - Fork 135
/
dfs_stacks.cpp
80 lines (70 loc) · 1.75 KB
/
dfs_stacks.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
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
#include<bits/stdc++.h>
using namespace std;
// graph class
class Graph
{
int V; // No. of vertices
list<int> *adjList; // adjacency lists
public:
Graph(int V) //graph Constructor
{
this->V = V;
adjList = new list<int>[V];
}
void addEdge(int v, int w) // add an edge to graph
{
adjList[v].push_back(w); // Add w to v’s list.
}
void DFS(); // DFS traversal
// utility function called by DFS
void DFSUtil(int s, vector<bool> &visited);
};
//traverses all not visited vertices reachable from start node s
void Graph::DFSUtil(int s, vector<bool> &visited)
{
// stack for DFS
stack<int> dfsstack;
// current source node inside stack
dfsstack.push(s);
while (!dfsstack.empty())
{
// Pop a vertex
s = dfsstack.top();
dfsstack.pop();
// display the item or node only if its not visited
if (!visited[s])
{
cout << s << " ";
visited[s] = true;
}
// explore all adjacent vertices of popped vertex.
//Push the vertex to the stack if still not visited
for (auto int i = adjList[s].begin(); i != adjList[s].end(); ++i)
if (!visited[*i])
dfsstack.push(*i);
}
}
// DFS
void Graph::DFS()
{
// initially all vertices are not visited
vector<bool> visited(V, false);
for (int i = 0; i < V; i++)
if (!visited[i])
DFSUtil(i, visited);
}
//main program
int main()
{
Graph gidfs(5); //create graph
gidfs.addEdge(0, 1);
gidfs.addEdge(0, 2);
gidfs.addEdge(0, 3);
gidfs.addEdge(1, 2);
gidfs.addEdge(2, 4);
gidfs.addEdge(3, 3);
gidfs.addEdge(4, 4);
cout << "Output of Iterative Depth-first traversal:\n";
gidfs.DFS();
return 0;
}