Graph Representation

VV
2 min readJun 22, 2021

Note : if no of edges is N & no of vertices is M then

if value of nodes are 0-indexed i.e 0,1,2,3,,,, then adjacency matrix and list are of size M+1,N+1 for matrix && N+1 for list

else if 1 based indexed then take M,N & N only

Adjacency Matrix (directed) (space is O(V²)

#include <iostream>using namespace std;bool A[100][100];void initialize()
{
for(int i = 0;i < 10;++i)
for(int j = 0;j < 10;++j)
A[i][j] = false;
}
int main()
{
int x, y, nodes, edges;
initialize(); //Since there is no edge initially
cin >> nodes; //Number of nodes
cin >> edges; //Number of edges
for(int i = 0;i < edges;++i)
{
cin >> x >> y;
A[x][y] = true;
//Mark the edges from vertex x to vertex y
}
// EXAMPLE
if(A[3][4] == true)
cout << “There is an edge between 3 and 4” << endl;
else
cout << “There is no edge between 3 and 4” << endl;
return 0;
}

Adjacency List (directed) (space is O(V + 2*E)

#include<iostream >
#include < vector >
using namespace std; vector <int> adj[10]; // array of vectors// or use unordered_map<int, vector<int> > adj;
int main()
{
int x, y, nodes, edges;
cin >> nodes; //Number of nodes
cin >> edges; //Number of edges
for(int e= 0;e < edges;++e)
{
cin >> x >> y;
adj[x].push_back(y); //Insert y in adjacency list of x
}
for(int v= 0;v < nodes;++v)
{
cout << "Adjacency list of node " << v+1<< ": ";
for(int j = 0;j < adj[v].size();++j)
cout << adj[i][j] << " --> ";

cout<<endl;
}
}
return 0;
}

If there is weight n edges too then take array of vector<pair<int,int>> arr[ ]

--

--