-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs_stack.cpp
118 lines (95 loc) · 2.08 KB
/
dfs_stack.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
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
// assume all vertices are numbered from 0 to V - 1
#include<iostream>
#include<stdio.h>
#include<list>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
class Graph
{
unsigned int V;
list<unsigned int> *adj;
void DfsUtil(unsigned int v,bool visited[]);
public:
Graph(unsigned int V);
void DFS(unsigned int v);
void DFSComplete();
void addEdge(unsigned int s,unsigned int d);
};
Graph::Graph(unsigned int V)
{
this->V = V;
this->adj = new list<unsigned int>[V];
}
void Graph::addEdge(unsigned int s, unsigned int d)
{
this->adj[s].push_back(d);
}
void Graph::DFS(unsigned int v)
{
bool *visited = new bool[this->V];
for(unsigned int i = 0; i < this->V ; i++)
visited[i] = false;
this->DfsUtil(v,visited);
}
void Graph::DfsUtil(unsigned int v,bool visited[])
{
stack<unsigned int> dfsStack;
dfsStack.push(v);
visited[v] = true;
while(!dfsStack.empty())
{
unsigned int vv = dfsStack.top();
visited[vv] = true;
printf("%u ",vv);
dfsStack.pop();
list<unsigned int>::iterator it;
for(it = adj[vv].begin(); it != adj[vv].end(); it++)
{
if(!visited[*it])
{
dfsStack.push(*it);
visited[*it] = true;
}
}
}
}
void Graph::DFSComplete()
{
bool *visited = new bool[this->V];
for(unsigned int i = 0; i < this->V; i++)
{
visited[i] = false;
}
for(unsigned int v = 0; v < this->V; v++)
{
if(!visited[v])
{
this->DfsUtil(v,visited);
}
}
}
int main()
{
fflush(stdout);
Graph g(3);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(2,1);
/*
Graph g(4);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(2,0);
g.addEdge(2,3);
g.addEdge(3,3);
*/
g.DFS(0);
printf("\nall nodes in the Graph:\n");
g.DFSComplete();
printf("\n");
return 0;
}