-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs&dfs.cpp
More file actions
115 lines (92 loc) · 2.63 KB
/
bfs&dfs.cpp
File metadata and controls
115 lines (92 loc) · 2.63 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
#include <iostream>
using namespace std;
class Graph {
int **adjMatrix;
int vertices;
public:
void createGraph(int v, int e) {
vertices = v;
adjMatrix = new int*[vertices];
for (int i = 0; i < vertices; i++) {
adjMatrix[i] = new int[vertices];
for (int j = 0; j < vertices; j++) {
adjMatrix[i][j] = 0;
}
}
int u, ver;
for (int i = 0; i < e; i++) {
cout << "Enter edge " << i + 1 << " (format: u v): ";
cin >> u >> ver;
if (u < 0 || u >= vertices || ver < 0 || ver >= vertices) {
cout << "Invalid edge! Vertex numbers should be between 0 and " << vertices - 1 << ".\n";
i--;
continue;
}
adjMatrix[u][ver] = 1;
adjMatrix[ver][u] = 1; // Remove for directed graph
}
}
void dfs(int start, int *visited) {
cout << start << " ";
visited[start] = 1;
for (int i = 0; i < vertices; i++) {
if (adjMatrix[start][i] == 1 && !visited[i]) {
dfs(i, visited);
}
}
}
void bfs(int start) {
int *visited = new int[vertices];
for (int i = 0; i < vertices; i++) visited[i] = 0;
int *queue = new int[vertices];
int front = 0, rear = 0;
queue[rear++] = start;
visited[start] = 1;
while (front < rear) {
int node = queue[front++];
cout << node << " ";
for (int i = 0; i < vertices; i++) {
if (adjMatrix[node][i] == 1 && !visited[i]) {
queue[rear++] = i;
visited[i] = 1;
}
}
}
delete[] visited;
delete[] queue;
}
void startDFS(int start) {
int *visited = new int[vertices];
for (int i = 0; i < vertices; i++) visited[i] = 0;
cout << "DFS Traversal: ";
dfs(start, visited);
cout << endl;
delete[] visited;
}
void startBFS(int start) {
cout << "BFS Traversal: ";
bfs(start);
cout << endl;
}
void deleteGraph() {
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
}
};
int main() {
Graph g;
int v, e, start;
cout << "Enter number of vertices: ";
cin >> v;
cout << "Enter number of edges: ";
cin >> e;
g.createGraph(v, e);
cout << "Enter starting vertex for DFS and BFS: ";
cin >> start;
g.startDFS(start);
g.startBFS(start);
g.deleteGraph();
return 0;
}