Adjacency Matrix
A V×V 2-D array where matrix[u][v] holds the edge weight (or 1/0 for unweighted graphs), giving O(1) edge lookups at the cost of O(V²) space.
Syntax
// 0-indexed vertices
const matrix = Array.from({ length: V }, () => new Array(V).fill(0));
matrix[u][v] = weight; // directed
matrix[v][u] = weight; // also this for undirected
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
V | number | Yes | Number of vertices. The matrix is V × V. |
directed | boolean | No | When false (default) the matrix is symmetric: setting matrix[u][v] also sets matrix[v][u]. |
Returns
number[][] — A V×V 2-D array representing the graph.
Examples
function adjMatrix(V, edges, directed = false) {
const m = Array.from({ length: V }, () => new Array(V).fill(0));
for (const [u, v, w = 1] of edges) {
m[u][v] = w;
if (!directed) m[v][u] = w;
}
return m;
}
const m = adjMatrix(4, [[0,1],[0,2],[1,3],[2,3]]);
m.forEach((row, i) => console.log(`${i}: ${row}`));
Output
0: 0,1,1,0
1: 1,0,0,1
2: 1,0,0,1
3: 0,1,1,0
// Floyd-Warshall all-pairs shortest paths (O(V³))
function floydWarshall(dist) {
const V = dist.length;
for (let k = 0; k < V; k++)
for (let i = 0; i < V; i++)
for (let j = 0; j < V; j++)
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
return dist;
}
const INF = Infinity;
const d = [[0,3,INF,5],[2,0,INF,4],[INF,1,0,INF],[INF,INF,2,0]];
console.log(floydWarshall(d)[0]);
Output
[ 0, 3, 9, 5 ]
Notes
| Operation | Time | Space |
|-------------------|------|--------|
| Add/remove edge | O(1) | O(1) |
| Check edge (u,v) | O(1) | O(1) |
| Iterate neighbors | O(V) | O(1) |
| Total space | — | O(V²) |
Use when V is small (< ~10,000) or when the graph is dense (E ≈ V²).
For weighted graphs store weights instead of 1/0; use Infinity (or
Number.MAX_SAFE_INTEGER) to represent absent edges.
An adjacency list is more memory-efficient for sparse graphs.