graph c++
//code by Soumyadeep Ghosh
//insta : @soumyadepp
//linked in: https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
#include <bits/stdc++.h>
using namespace std;
//undirected weighted graph
class WeightedGraph
{
vector< pair<int,int> >*adjacency_list;
int vertices;
public:
WeightedGraph(int n)
{
vertices=n;
adjacency_list=new vector< pair<int,int> >[n];
}
void add_edge(int v1,int v2,int wt);
void display_graph();
};
int main()
{
//graph of five vertices
WeightedGraph wg1(5);
//adding edges
wg1.add_edge(0,1,10);
wg1.add_edge(1,2,20);
wg1.add_edge(2,3,30);
wg1.add_edge(1,3,40);
wg1.add_edge(2,4,100);
wg1.add_edge(4,0,10);
//displaying the graph
wg1.display_graph();
return 0;
}
//function definitions
void WeightedGraph::add_edge(int v1,int v2,int wt)
{
/*push the other vertex into the adjacency list of the given vertex
and vice versa. If it would have been a directed graph,
only the first line would be enough
*/
adjacency_list[v1].push_back(make_pair(v2,wt));
adjacency_list[v2].push_back(make_pair(v1,wt));
}
void WeightedGraph::display_graph()
{
int a,b;
//first loop to traverse across vertices
for(int i=0;i<vertices;i++)
{
cout<<"Adjacency list of vertex "<<i<<endl;
//second loop to traverse across the adjacency list of some vertex i
for(auto it=adjacency_list[i].begin();it!=adjacency_list[i].end();it++)
{
//set a as the vertex number and b as the weight
a=it->first;
b=it->second;
cout<<"Vertex : "<<a<<" Weight : "<<b<<endl;
}
cout<<endl;
}
}
//thank you!
//Code by Soumyadeep Ghosh insta- @soumyadepp
//linked in : https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
//Basic implementation of undirected graph using OOP
#include <bits/stdc++.h>
using namespace std;
//undirected graph
class graph
{
vector<int>*adjacency_list; //array of vectors to store adjacency list
int Vertices;
public:
//constructor
graph(int n)
{
Vertices=n;
adjacency_list=new vector<int>[Vertices]; //dynamic allocation
}
void add_edge(int,int);
void display_graph();
};
int main()
{
graph g1(5); //graph of 5 vertices indices- 0 to 4
//adding edges
g1.add_edge(0,1); //connect node number 0 to node number 1
g1.add_edge(1,2); //connect node number 1 to node number 2
g1.add_edge(1,3); //connect node number 1 to node number 3
g1.add_edge(2,4); //connect node number 2 to node number 4
g1.add_edge(2,3); //connect node number 2 to node number 3
//displaying the graph
cout<<"The entered Graph is "<<endl;
g1.display_graph();
return 0;
}
//function definitions
void graph::add_edge( int u,int v )
{
if( u >= Vertices || v >= Vertices )
{
cout<<"Overflow"<<endl;
return;
}
if( u<0 || v<0 )
{
cout<<"underflow"<<endl;
return;
}
adjacency_list[u].push_back(v);
adjacency_list[v].push_back(u);
}
void graph::display_graph()
{
for(int i=0;i<Vertices;i++)
{
cout<<"Adjacency list of vertex of vertex "<<i<<endl;
for(auto it:adjacency_list[i]) //traverse through each list
{
cout<<it<<" ";
}
cout<<endl;
}
}
//thank you!