Graphs can be represented in two common ways: adjacency matrices and adjacency lists. Each representation has its own advantages and disadvantages, depending on the nature of the graph and the operations being performed.
An adjacency matrix is a 2D array (or matrix) used to represent a graph. For a graph with vertices, it is an matrix where each cell indicates whether there is an edge from vertex to vertex .
1 (or true) indicates the presence of an edge.0 (or false) indicates no edge.Properties:
Example Implementation:
#include <iostream>
#include <vector>
using namespace std;
class Graph {
private:
vector<vector<int>> adjMatrix;
int numVertices;
public:
Graph(int vertices) : numVertices(vertices) {
adjMatrix.resize(vertices, vector<int>(vertices, 0)); // Initialize to 0
}
void addEdge(int u, int v) {
adjMatrix[u][v] = 1; // Directed graph
// adjMatrix[v][u] = 1; // Uncomment for undirected graph
}
void printGraph() {
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
};
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.printGraph();
return 0;
}
An adjacency list is a more space-efficient way to represent a graph. It uses an array (or vector) of lists (or vectors), where each index represents a vertex and contains a list of all adjacent vertices (i.e., those with which it shares an edge).
Properties:
Example Implementation:
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Graph {
private:
vector<list<int>> adjList;
int numVertices;
public:
Graph(int vertices) : numVertices(vertices) {
adjList.resize(vertices);
}
void addEdge(int u, int v) {
adjList[u].push_back(v); // Directed graph
// adjList[v].push_back(u); // Uncomment for undirected graph
}
void printGraph() {
for (int i = 0; i < numVertices; i++) {
cout << "Vertex " << i << ":";
for (int v : adjList[i]) {
cout << " -> " << v;
}
cout << endl;
}
}
};
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.printGraph();
return 0;
}
Both adjacency matrices and adjacency lists are effective ways to represent graphs, but they serve different needs:
Adjacency Matrix:
Adjacency List:
Choosing the right representation depends on the specific use case and the characteristics of the graph being modeled.
Open this section to load past papers