-
Notifications
You must be signed in to change notification settings - Fork 0
/
12a_dfs_graph.cpp
111 lines (88 loc) · 2.43 KB
/
12a_dfs_graph.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
// 12. Implement Graph Traversal techniques:
// a) Depth First Search
// Theory:
// This code implements depth-first search (DFS) traversal on an
// undirected graph represented using an adjacency matrix. It
// constructs the graph by adding edges between vertices, then
// performs DFS traversal starting from a specified vertex. DFS
// explores as far as possible along each branch before backtracking.
#include <iostream>
#include <stack>
using namespace std;
const int MAX_VERTICES = 100;
class Graph
{
int V;
int** adj;
public:
Graph(int V)
{
this->V = V;
adj = new int*[V];
for (int i = 0; i < V; ++i)
{
adj[i] = new int[V];
for (int j = 0; j < V; ++j)
{
adj[i][j] = 0;
}
}
}
void addEdge(int v, int w)
{
adj[v][w] = 1;
adj[w][v] = 1;
}
void DFS(int v)
{
bool* visited = new bool[V];
for (int i = 0; i < V; ++i)
visited[i] = false;
stack<int> stack;
visited[v] = true;
stack.push(v);
while (!stack.empty())
{
v = stack.top();
stack.pop();
cout << v << " ";
for (int i = 0; i < V; ++i)
{
if (adj[v][i] && !visited[i])
{
visited[i] = true;
stack.push(i);
}
}
}
delete[] visited;
}
};
int main()
{
int V, E;
cout << "enter number of vertices & edges: ";
cin >> V >> E;
Graph g(V);
cout << "enter edges:" << endl;
for (int i = 0; i < E; ++i)
{
int v, w;
cin >> v >> w;
g.addEdge(v, w);
}
int start_vertex;
cout << "enter starting vertex: ";
cin >> start_vertex;
cout << "Depth First Traversal: ";
g.DFS(start_vertex);
return 0;
}
// Conclusion:
// The code efficiently performs DFS traversal on an undirected graph
// using an adjacency matrix representation. It constructs the graph
// by adding edges between vertices and then executes DFS from a
// specified starting vertex. The DFS algorithm explores each vertex
// & its adjacent vertices in depth-first manner, ensuring that all
// reachable vertices are visited. Overall, the code provides a clear
// & effective implementation of DFS traversal on an undirected graph.