This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
forked from abhishekchopra13/nwoc_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 52
/
DFS_BFS_in_Graphs.cpp
76 lines (72 loc) · 1.54 KB
/
DFS_BFS_in_Graphs.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
#include <bits/stdc++.h>
using namespace std;
class Graph {
int v;
int e;
int matrix[10][10];
public:
Graph(int v, int e);
void addEdge(int start, int e);
void DFS(int start, vector<bool>& flags);
void BFS(int start);
};
Graph::Graph(int vertices, int edges)
{
v = vertices;
e = edges;
for (int row = 0; row < v; row++) {
for (int column = 0; column < v; column++) {
matrix[row][column] = 0;
}
}
}
void Graph::addEdge(int start, int end)
{
matrix[start][end] = 1;
matrix[end][start] = 1;
}
void Graph::DFS(int start, vector<bool>& flags)
{
cout << start << " ";
flags[start] = true;
for (int i = 0; i < v; i++) {
if (matrix[start][i] == 1 && (!flags[i])) {
DFS(i, flags);
}
}
}
void Graph::BFS(int start)
{
vector<bool> flags(v, false);
vector<int> q;
q.push_back(start);
flags[start] = true;
int vis;
cout<<"BFS: ";
while (!q.empty()) {
vis = q[0];
cout << vis << " ";
q.erase(q.begin());
for (int i = 0; i < v; i++) {
if (matrix[vis][i] == 1 && (!flags[i]))
{
q.push_back(i);
flags[i] = true;
}
}
}
}
int main()
{
int v = 5, e = 4;
Graph G(v, e);
G.addEdge(0, 1);
G.addEdge(1, 2);
G.addEdge(1, 3);
G.addEdge(2, 4);
vector<bool> flags(v, false);
cout<<"DFS: " ;
G.DFS(0, flags);
cout<<endl;
G.BFS(0);
}