8000 Merge pull request #1163 from milanj-1/dev · oo7dotcom/Algorithms@281dfc7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 281dfc7

Browse files
authored
Merge pull request VAR-solutions#1163 from milanj-1/dev
Create iterative_dfs.cpp
2 parents f59f09f + a51843c commit 281dfc7

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Graphs/dfs/cpp/iterative_dfs.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// An Iterative C++ program to do DFS traversal from
2+
// a given source vertex. DFS(int s) traverses vertices
3+
// reachable from s.
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
7+
// This class represents a directed graph using adjacency
8+
// list representation
9+
class Graph
10+
{
11+
int V; // No. of vertices
12+
list<int> *adj; // adjacency lists
13+
public:
14+
Graph(int V); // Constructor
15+
void addEdge(int v, int w); // to add an edge to graph
16+
void DFS(int s); // prints all vertices in DFS manner
17+
// from a given source.
18+
};
19+
20+
Graph::Graph(int V)
21+
{
22+
this->V = V;
23+
adj = new list<int>[V];
24+
}
25+
26+
void Graph::addEdge(int v, int w)
27+
{
28+
adj[v].push_back(w); // Add w to v’s list.
29+
}
30+
31+
// prints all not yet visited vertices reachable from s
32+
void Graph::DFS(int s)
33+
{
34+
// Initially mark all verices as not visited
35+
vector<bool> visited(V, false);
36+
37+
// Create a stack for DFS
38+
stack<int> stack;
39+
40+
// Push the current source node.
41+
stack.push(s);
42+
43+
while (!stack.empty())
44+
{
45+
// Pop a vertex from stack and print it
46+
s = stack.top();
47+
stack.pop();
48+
49+
// Stack may contain same vertex twice. So
50+
// we need to print the popped item only
51+
// if it is not visited.
52+
if (!visited[s])
53+
{
54+
cout << s << " ";
55+
visited[s] = true;
56+
}
57+
58+
// Get all adjacent vertices of the popped vertex s
59+
// If a adjacent has not been visited, then push it
60+
// to the stack.
61+
for (auto i = adj[s].begin(); i != adj[s].end(); ++i)
62+
if (!visited[*i])
63+
stack.push(*i);
64+
}
65+
}
66+
67+
// Driver program to test methods of graph class
68+
int main()
69+
{
70+
Graph g(5); // Total 5 vertices in graph
71+
g.addEdge(1, 0);
72+
g.addEdge(0, 2);
73+
g.addEdge(2, 1);
74+
g.addEdge(0, 3);
75+
g.addEdge(1, 4);
76+
77+
cout << "Following is Depth First Traversal\n";
78+
g.DFS(0);
79+
80+
return 0;
81+
}

0 commit comments

Comments
 (0)
0