-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs_dfs.cpp
More file actions
132 lines (93 loc) · 2.55 KB
/
bfs_dfs.cpp
File metadata and controls
132 lines (93 loc) · 2.55 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
void BFS(int edge[][50], int v, int start) {
bool visited[50] = {false};
queue<int> q;
visited[start] = true;
q.push(start);
cout << "\nBFS Traversal: ";
while (!q.empty()) {
int node = q.front();
q.pop();
cout << "v" << node + 1 << " ";
for (int i = 0; i < v; i++) {
if (edge[node][i] > 0 && !visited[i]) {
visited[i] = true;
q.push(i);
}
}
}
}
void DFS(int edge[][50], int v, int start) {
bool visited[50] = {false};
stack<int> s;
s.push(start);
cout << "\nDFS Traversal: ";
while (!s.empty()) {
int node = s.top();
s.pop();
if (!visited[node]) {
visited[node] = true;
cout << "v" << node + 1 << " ";
for (int i = v - 1; i >= 0; i--) {
if (edge[node][i] > 0 && !visited[i]) {
s.push(i);
}
}
}
}
}
void createGraph(int edge[][50], int &v) {
int e;
char type;
cout << "Enter number of vertices: ";
cin >> v;
cout << "Undirected or Directed graph? (u/d): ";
cin >> type;
for (int i = 0; i < v; i++)
for (int j = 0; j < v; j++)
edge[i][j] = 0;
if (type == 'u') {
for (int i = 0; i < v; i++) {
for (int j = i; j < v; j++) {
cout << "How many edges between v" << i + 1 << " and v" << j + 1 << ": ";
cin >> e;
edge[i][j] = e;
edge[j][i] = e;
}
}
}
else if (type == 'd') {
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
cout << "How many directed edges from v" << i << " to v" << j << ": ";
cin >> e;
edge[i - 1][j - 1] = e;
}
}
}
else {
cout << "Wrong Input!";
return;
}
cout << "\nAdjacency Matrix:\n";
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
cout << edge[i][j] << " ";
}
cout << endl;
}
}
int main() {
int edge[50][50];
int v;
createGraph(edge, v);
int start;
cout << "\nEnter starting vertex (1-" << v << "): ";
cin >> start;
BFS(edge, v, start - 1);
DFS(edge, v, start - 1);
return 0;
}