AlgoFrames

Edge list to matrix

Standard · Write code · about 7 min

graph has vertices 0 to n - 1 and an edge list edges. Return its n × n adjacency matrix with 1 for an edge and 0 otherwise.

When graph.directed is false, an edge [u, v] sets both matrix[u][v] and matrix[v][u]. An edge listed twice is still a single 1.

Example 1

Input:

[{"n":5,"edges":[[0,1],[0,2],[1,2],[1,3],[2,3],[3,4]],"directed":false}]

Output:

[[0,1,1,0,0],[1,0,1,1,0],[1,1,0,1,0],[0,1,1,0,1],[0,0,0,1,0]]

Undirected, so the matrix is symmetric.

Example 2

Input:

[{"n":4,"edges":[[0,1],[1,2],[2,0],[2,3]],"directed":true}]

Output:

[[0,1,0,0],[0,0,1,0],[1,0,0,1],[0,0,0,0]]

Directed: 0 → 1 sets only row 0, column 1.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ 1,000
  • 0 ≤ u, v < n

Learn the idea first: Adjacency matrix, adjacency list, edge list, a visual lesson.

More Adjacency matrix, adjacency list, edge list problems