-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgos1
More file actions
169 lines (135 loc) · 2.17 KB
/
algos1
File metadata and controls
169 lines (135 loc) · 2.17 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
163
164
165
166
167
168
169
#include<iostream>
#include<vector>
#include<limits.h>
#include<string>
#include<list>
class Graph
{
int vertices;
std::list<int>* adjlist;
int* visited;
public:
Graph(int v);
void addEdge(int src, int dest);
void displaylist();
void bfs(int sv);
void dfs(int sv);
void tps(int sv);
};
Graph::Graph(int v)
{
vertices = v;
adjlist = new std::list<int>[v];
visited = new int[v] {0};
}
void Graph::addEdge(int src, int dest)
{
adjlist[src].push_back(dest);
}
void Graph::displaylist()
{
for (int i = 0; i < vertices; i++)
{
std::cout << i << " :";
for (auto k : adjlist[i])
{
std::cout << " -->" << k;
}
std::cout << std::endl;
}
}
void Graph::bfs(int sv)
{
visited[sv] = 1;
int current;// stores the dequeued node.
std::list<int> queue;
queue.push_front(sv);
while (!queue.empty())
{
current = queue.front();
visited[current] = 1;
queue.pop_front();
std::cout << current << " ";
for (auto i : adjlist[current])
{
if (visited[i] != 1)
{
queue.push_back(i);
visited[i] = 1;
}
}
}
delete[] visited;
}
void Graph::dfs(int sv)
{
visited[sv] = 1;
std::cout << sv << " ";
for (auto x : adjlist[sv])
{
if (visited[x] == 0)
{
visited[x] = 1;
dfs(x);
}
}
}
void Graph::tps(int sv)
{
int* start = new int[vertices] {0};
std::list<int> tps;
std::list<int> stack;
stack.push_front(sv);
start[sv] = 1;
std::cout << sv << " ";
int current;
int t = 1; // traversal index.
for (int i = 0; i < vertices; i++)
{
if (start[i] == 0 && stack.empty())
{
stack.push_front(i);
start[i] = ++t;
}
int temp;
while (!stack.empty())
{
current = stack.front();
bool flag = true;
for (auto x : adjlist[current])
{
if (start[x] == 0)
{
flag = false;
std::cout << x << " ";
start[x] = ++t;
stack.push_front(x);
}
}
if (flag)
{
tps.push_front(stack.front());
stack.pop_front();
}
}
//
}
std::cout << "\n";
for (auto x : tps)
{
std::cout << x << " ";
}
}
int main()
{
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.displaylist();
g.dfs(2);
return 0;
}