-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraph.cpp
More file actions
126 lines (108 loc) · 3.14 KB
/
Graph.cpp
File metadata and controls
126 lines (108 loc) · 3.14 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
#include<bits/stdc++.h>
using namespace std;
class Graph
{
public:
vector<vector<int>> graph;
int size = 100;
Graph(int n=100){
cout << "Graph is initiated with a max size of 100" << endl;
size = n;
graph.resize(n);
}
void insert_edge(int a, int b){
graph[a].push_back(b);
graph[b].push_back(a);
}
void print(int v = 0){
for (int vertice = 0; vertice < size; vertice++){
if(graph[vertice].size() == 0){ continue;}
cout << "Vertice is " << vertice << endl;
cout << " Edges are --> ";
for(auto edges:graph[vertice]){
cout << edges << " ";
}
cout << endl;
}
}
void bfs(int v = 0){
bool check[size]={0};
queue<int> q;
for(int i=v;i<size;i++){
if(graph[i].size() == 0){continue;}
q.push(i);
check[i] = true;
break;
}
if(v == 0)
cout << "Starting the BFS of the Graph from the node with minimum value..!" << endl;
else
cout << "Starting the BFS of the Graph from the node with value of " << v << endl;
cout << q.front() << " --> ";
check[q.front()] = true;
while(!q.empty()){
int top = q.front();
if(!check[top]){
cout << top << " --> ";
}
q.pop();
for(auto x:graph[top]){
if(!check[x]){
cout << x << " --> ";
q.push(x);
check[x] = 1;
}
}
}
cout << endl;
}
void dfs(int v = 0){
bool check[size]={0};
stack<int> s;
for(int i=v;i<size;i++){
if(graph[i].size() == 0){continue;}
s.push(i);
check[i] = true;
break;
}
if(v == 0)
cout << "Starting the DFS of the Graph from the node with minimum value..!" << endl;
else
cout << "Starting the DFS of the Graph from the node with value of " << v << endl;
cout << s.top() << " --> ";
check[s.top()] = true;
while(!s.empty()){
int top = s.top();
if(!check[top]){
cout << top << " --> ";
check[top] = true;
}
s.pop();
for(auto x:graph[top]){
if(!check[x]){
s.push(x);
//check[x] = true;
}
}
}
}
};
int main(){
int n;
cout << "Enter how many edges you want to make.." << endl;
cin >> n;
Graph graph;
for(int i=0;i<n;i++){
int a,b;
cout << "Enter the values " << endl;
cin >> a >> b;
graph.insert_edge(a,b);
}
graph.print();
cout << "Enter from which node, you want to start the bfs traversal" << endl;
int bf; cin >> bf;
graph.bfs(bf);
cout << "Enter from which node, you want to start the dfs traversal" << endl;
int df; cin >> df;
graph.dfs(df);
}