Graphs are abstract data structures consisting of nodes (vertices) connected by edges. Representing a graph in a computer efficiently is critical to perform various graph algorithms such as traversal, shortest path, and connectivity.
An adjacency matrix is a 2D array of size V x V
where V is the number of vertices. The element at row i
and column j
is 1
(or the weight of edge) if there is an edge from vertex i
to vertex j
, otherwise 0
.
V²
space.def create_adj_matrix(vertices, edges):
graph = [[0] * vertices for _ in range(vertices)]
for (src, dst) in edges:
graph[src][dst] = 1 # Directed graph
# For undirected, add graph[dst][src] = 1
return graph
vertices = 4
edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
adj_matrix = create_adj_matrix(vertices, edges)
for row in adj_matrix:
print(row)
An adjacency list represents a graph as an array (or dictionary) of lists. Each index represents a vertex; its list contains all adjacent vertices (neighbors).
function addEdge(adj, src, dst) {
adj[src].push(dst);
// For undirected graph, add:
// adj[dst].push(src);
}
const vertices = 4;
const adj = Array.from({ length: vertices }, () => []);
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
adj.forEach((neighbors, vertex) => {
console.log(vertex + ": " + neighbors.join(", "));
});
Representation | Space Complexity | Edge Lookup Time | Best Use Case |
---|---|---|---|
Adjacency Matrix | O(V²) | O(1) | Dense graphs with many edges |
Adjacency List | O(V + E) | O(V) to check neighbors | Sparse graphs with fewer edges |