-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphDfs.cpp
More file actions
90 lines (70 loc) · 1.41 KB
/
GraphDfs.cpp
File metadata and controls
90 lines (70 loc) · 1.41 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
//DFS Traversal Of Unidirected Graph
#include<bits/stdc++.h>
#define ll long long
using namespace std;
template<typename T>
class Graph {
private:
int numVertices;
list<T> *adjLists;
bool* visited;
public:
Graph(T);
void addEdge(T , T );
void DFS(T);
};
//Initialize Graph
template<class T>
Graph<T>::Graph(T vertices) {
numVertices = vertices;
adjLists = new list<T>[vertices];
visited = new bool[vertices];
}
//Add Edges
template<class T>
void Graph<T>::addEdge(T src, T dest) {
adjLists[src].push_front(dest);
adjLists[dest].push_front(src); //For Directed Remove This Line
}
//DFS Algorithms
template<class T>
void Graph<T>::DFS(T vertex) {
visited[vertex] = true;
list<T> adjList = adjLists[vertex];
cout << vertex << " ";
list<int>::iterator i;
for (i = adjList.begin(); i != adjList.end(); ++i) {
if (!visited[*i])
DFS(*i);
}
}
int main() {
// TestCase 1:
Graph<int> g(5);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(1, 4);
g.addEdge(3, 4);
//TestCase 2:
// Graph g(4);
// g.addEdge(0, 1);
// g.addEdge(0, 2);
// g.addEdge(1, 2);
// g.addEdge(2, 3);
//Test 3:
// Graph g(7);
// g.addEdge(0, 4);
// g.addEdge(0, 3);
// g.addEdge(0, 1);
// g.addEdge(1, 6);
// g.addEdge(1, 5);
// g.addEdge(1, 2);
g.DFS(1);
return 0;
}
/*** Output
1 4 3 2 0
1 2 3 0
1 2 5 6 0 3 4
***/