-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfsStack.cpp
55 lines (42 loc) · 942 Bytes
/
dfsStack.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
#include<bits/stdc++.h>
using namespace std;
class graph{
public:
int v;
list<int> *adj;
graph(int v){
this->v = v;
adj = new list<int>[v];
}
void addEdge(int v, int w){
adj[v].push_back(w);
}
void dfs(int s){
vector<bool> visited(v, false);
stack<int> st;
st.push(s);
while(!st.empty()){
int s = st.top();
st.pop();
if(!visited[s]){
cout<<s<<" ";
visited[s] = true;
}
for(auto i = adj[s].begin(); i != adj[s].end(); i++){
if(!visited[*i])
st.push(*i);
}
}
}
};
int main(){
graph g(5);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(1, 4);
cout << "Following is Depth First Traversal\n";
g.dfs(0);
return 0;
}