1//Code by Soumyadeep Ghosh insta- @soumyadepp
2//linked in : https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
3//Basic implementation of undirected graph using OOP
4
5#include <bits/stdc++.h>
6
7using namespace std;
8
9//undirected graph
10class graph
11{
12 vector<int>*adjacency_list; //array of vectors to store adjacency list
13 int Vertices;
14 public:
15 //constructor
16 graph(int n)
17 {
18 Vertices=n;
19 adjacency_list=new vector<int>[Vertices]; //dynamic allocation
20 }
21
22 void add_edge(int,int);
23 void display_graph();
24};
25
26int main()
27{
28 graph g1(5); //graph of 5 vertices indices- 0 to 4
29 //adding edges
30 g1.add_edge(0,1); //connect node number 0 to node number 1
31 g1.add_edge(1,2); //connect node number 1 to node number 2
32 g1.add_edge(1,3); //connect node number 1 to node number 3
33 g1.add_edge(2,4); //connect node number 2 to node number 4
34 g1.add_edge(2,3); //connect node number 2 to node number 3
35 //displaying the graph
36 cout<<"The entered Graph is "<<endl;
37 g1.display_graph();
38 return 0;
39}
40
41//function definitions
42void graph::add_edge( int u,int v )
43 {
44 if( u >= Vertices || v >= Vertices )
45 {
46 cout<<"Overflow"<<endl;
47 return;
48 }
49 if( u<0 || v<0 )
50 {
51 cout<<"underflow"<<endl;
52 return;
53 }
54 adjacency_list[u].push_back(v);
55 adjacency_list[v].push_back(u);
56 }
57 void graph::display_graph()
58 {
59 for(int i=0;i<Vertices;i++)
60 {
61 cout<<"Adjacency list of vertex of vertex "<<i<<endl;
62 for(auto it:adjacency_list[i]) //traverse through each list
63 {
64 cout<<it<<" ";
65 }
66 cout<<endl;
67 }
68 }
69//thank you!
70