cons list java adjacency matrix code example
Example 1: graph using djacency matrix c++
#include <iostream>
using namespace std;
class Graph {
private:
bool** adjMatrix;
int numVertices;
public:
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVertices];
for (int i = 0; i < numVertices; i++) {
adjMatrix[i] = new bool[numVertices];
for (int j = 0; j < numVertices; j++)
adjMatrix[i][j] = false;
}
}
void addEdge(int i, int j) {
adjMatrix[i][j] = true;
adjMatrix[j][i] = true;
}
void removeEdge(int i, int j) {
adjMatrix[i][j] = false;
adjMatrix[j][i] = false;
}
void toString() {
for (int i = 0; i < numVertices; i++) {
cout << i << " : ";
for (int j = 0; j < numVertices; j++)
cout << adjMatrix[i][j] << " ";
cout << "\n";
}
}
~Graph() {
for (int i = 0; i < numVertices; i++)
delete[] adjMatrix[i];
delete[] adjMatrix;
}
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.toString();
}
Example 2: graph c++
#include <bits/stdc++.h>
using namespace std;
class graph
{
vector<int>*adjacency_list;
int Vertices;
public:
graph(int n)
{
Vertices=n;
adjacency_list=new vector<int>[Vertices];
}
void add_edge(int,int);
void display_graph();
};
int main()
{
graph g1(5);
g1.add_edge(0,1);
g1.add_edge(1,2);
g1.add_edge(1,3);
g1.add_edge(2,4);
g1.add_edge(2,3);
cout<<"The entered Graph is "<<endl;
g1.display_graph();
return 0;
}
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])
{
cout<<it<<" ";
}
cout<<endl;
}
}