-
Notifications
You must be signed in to change notification settings - Fork 0
/
c13.cpp
96 lines (83 loc) · 2.89 KB
/
c13.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
#include <iostream>
#include <queue>
using namespace std;
//----------------------------------------------------------------------------
class Graph {
private:
int numvertice;
vector<vector<int>> adjmatrix;
vector<vector<int>> adjlist;
//----------------------------------------------------------------------------
public:
Graph(int vertices) {
numvertice = vertices;
// Initialize adjacency matrix
adjmatrix.resize(numvertice, vector<int>(numvertice, 0));
// Initialize adjacency list
adjlist.resize(numvertice);
}
//----------------------------------------------------------------------------
void addEdge(int src, int dest) {
adjmatrix[src][dest] = 1;
adjmatrix[dest][src] = 1;
adjlist[src].push_back(dest);
adjlist[dest].push_back(src);
}
//----------------------------------------------------------------------------
void DFS(int startVertex, vector<bool>& visited) {
visited[startVertex] = true;
cout << startVertex << " ";
for (int i = 0; i < numvertice; ++i) {
if (adjmatrix[startVertex][i] == 1 && !visited[i]) {
DFS(i, visited);
}
}
}
//----------------------------------------------------------------------------
void DFS(int startVertex) {
vector<bool> visited(numvertice, false);
cout << "DFS Traversal: ";
DFS(startVertex, visited);
cout << endl;
}
//----------------------------------------------------------------------------
void BFS(int startVertex) {
vector<bool> visited(numvertice, false);
queue<int> bfsQueue;
visited[startVertex] = true;
bfsQueue.push(startVertex);
cout << "BFS Traversal: ";
//----------------------------------------------------------------------------
while (!bfsQueue.empty()) {
int currVertex = bfsQueue.front();
bfsQueue.pop();
cout << currVertex << " ";
for (int i = 0; i < adjlist[currVertex].size(); ++i) {
int adjVertex = adjlist[currVertex][i];
if (!visited[adjVertex]) {
visited[adjVertex] = true;
bfsQueue.push(adjVertex);
}
}
}
cout << endl;
}
};
//----------------------------------------------------------------------------
int main() {
// Create a graph
Graph graph(7);
// Add edges
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
graph.addEdge(2, 6);
// Perform DFS starting from vertex 0
graph.DFS(0);
// Perform BFS starting from vertex 0
graph.BFS(0);
return 0;
}
//----------------------------------------------------------------------------