-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfsdfs.cpp
More file actions
112 lines (93 loc) · 2.49 KB
/
bfsdfs.cpp
File metadata and controls
112 lines (93 loc) · 2.49 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
#include <iostream>
using namespace std;
class Graph {
int **adjMatrix;
int vertices;
public:
Graph(int v) {
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;
}
}
}
void addEdge(int u, int v) {
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1;
}
void DFS(int start) {
int *stack = new int[vertices];
int *visited = new int[vertices];
int top = -1;
for (int i = 0; i < vertices; i++) {
visited[i] = 0;
}
stack[++top] = start;
visited[start] = 1;
cout << "DFS Traversal: ";
while (top != -1) {
int node = stack[top--];
cout << node << " ";
for (int i = vertices - 1; i >= 0; i--) {
if (adjMatrix[node][i] == 1 && visited[i] == 0) {
stack[++top] = i;
visited[i] = 1;
}
}
}
cout << endl;
delete[] stack;
delete[] visited;
}
void BFS(int start) {
int *queue = new int[vertices];
int *visited = new int[vertices];
int front = 0, rear = 0;
for (int i = 0; i < vertices; i++) {
visited[i] = 0;
}
queue[rear++] = start;
visited[start] = 1;
cout << "BFS Traversal: ";
while (front < rear) {
int node = queue[front++];
cout << node << " ";
for (int i = 0; i < vertices; i++) {
if (adjMatrix[node][i] == 1 && visited[i] == 0) {
queue[rear++] = i;
visited[i] = 1;
}
}
}
cout << endl;
delete[] queue;
delete[] visited;
}
~Graph() {
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
}
};
int main() {
int vertices, edges, u, v, start;
cout << "Enter number of vertices: ";
cin >> vertices;
Graph g(vertices);
cout << "Enter number of edges: ";
cin >> edges;
cout << "Enter edges (u v):" << endl;
for (int i = 0; i < edges; i++) {
cin >> u >> v;
g.addEdge(u, v);
}
cout << "Enter starting node for DFS and BFS: ";
cin >> start;
g.DFS(start);
g.BFS(start);
return 0;
}