-
Notifications
You must be signed in to change notification settings - Fork 7
/
62_Graph_DFS.cpp
130 lines (123 loc) · 2.78 KB
/
62_Graph_DFS.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
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
using namespace std;
#include <unordered_map>
#include <algorithm>
#include <list>
#include <vector>
#include <stack>
// template <typename int>
class GraphDFS
{
public:
unordered_map<int, list<int>> adjList;
vector<int> vertices;
void addEdge(int u, int v, bool directed)
{
if (v != -1)
{
adjList[u].push_back(v);
if (!directed)
{
adjList[v].push_back(u);
}
if (vertex_check(u))
{
vertices.push_back(u);
}
if (vertex_check(u))
{
vertices.push_back(u);
}
}
else
{
adjList[u];
if (vertex_check(u))
{
vertices.push_back(u);
}
}
}
bool vertex_check(int v)
{
auto vert = find(vertices.begin(), vertices.end(), v);
if (vert != vertices.end())
{
return false;
}
return true;
}
// DFS using STACK
void DFS(int vertex, unordered_map<int, bool> &visited)
{
stack<int> st;
if (!visited[vertex])
{
st.push(vertex);
visited[vertex] = true;
}
while (!st.empty())
{
int top = st.top();
cout << top << " ";
st.pop();
for (auto i : adjList[top])
{
if (!visited[i])
{
st.push(i);
visited[i] = true;
}
}
}
}
// DFS using RECURSION
// void DFS(int vertex, unordered_map<int, bool> &visited)
// {
// if (!visited[vertex])
// {
// cout<<vertex<<" ";
// visited[vertex] = true;
// }
// for (auto i : adjList[vertex])
// {
// if (!visited[i])
// {
// DFS(i,visited);
// }
// }
// }
void display()
{
for (auto i : adjList)
{
cout << i.first << " -> ";
for (auto j : i.second)
{
cout << j << " ";
}
cout << endl;
}
}
};
int main()
{
GraphDFS g;
g.addEdge(0, 3, 0);
g.addEdge(1, 3, 0);
g.addEdge(1, 2, 0);
g.addEdge(1, 4, 0);
g.addEdge(5, -1, 0); // for isolated vertex
unordered_map<int, bool> visited;
for (int i = 0; i < g.vertices.size(); i++)
{
visited[g.vertices[i]] = false;
}
cout << "DFS" << endl;
for (int i = 0; i < g.vertices.size(); i++)
{ // this loop is used in case if graph is disconnected.
g.DFS(g.vertices[i], visited);
}
// g.display();
return 0;
}