Search⌘ K
AI Features

Graph Representations: Adjacency Matrix vs. Adjacency List

Explore how to represent graphs in Java using adjacency matrices and adjacency lists. Understand the space and time trade-offs of each method, and learn when to choose one over the other depending on graph density and application requirements.

A graph can be represented in memory in different ways. Two of the most common representations are the adjacency matrix and the adjacency list. Each representation has its own advantages and limitations, and the best choice depends on the graph and the problem we want to solve.

Adjacency matrix

An adjacency matrix uses a 2D array to represent connections between vertices. If a graph has n vertices, then the matrix has n d7 n cells. Each row and column corresponds to a vertex.

If there is an edge between two vertices, the corresponding cell stores a value such as 1 or True. If there is no edge, the cell stores 0 or false. This makes it easy to see which pairs of vertices are connected.

An adjacency matrix is easy to implement and allows very fast checks of whether an edge exists ...