Matrix to list
Standard · Write code · about 8 min
matrix is an n × n adjacency matrix: matrix[u][v] is 1 when there is an edge from u to v, else 0. Return the adjacency list: entry u lists every v with matrix[u][v] = 1, in increasing order.
Example 1
Input:
[[[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]]]
Output:
[[1,2],[0,2,3],[0,1,3],[1,2,4],[3]]
Row 1 has 1s in columns 0, 2 and 3.
Example 2
Input:
[[[0,1,0,0],[0,0,1,0],[1,0,0,1],[0,0,0,0]]]
Output:
[[1],[2],[0,3],[]]
A directed graph: row 3 is all 0s, so list 3 is empty.
Constraints
- 1 ≤ n ≤ 100
- matrix[u][v] is 0 or 1
Learn the idea first: Adjacency matrix, adjacency list, edge list, a visual lesson.
More Adjacency matrix, adjacency list, edge list problems
- Build an adjacency list Warm-up
- Memory cost Warm-up
- Edge list to matrix Standard
- Look up an edge Standard
- Pick the representation Standard
- Degree from each representation Challenge