AlgoFrames

Degree from each representation

Challenge · Write code · about 12 min

One undirected graph with vertices 0 to n - 1 and no self-loops arrives in one of three forms, named by kind:

  • "edges": data is an edge list, each edge [u, v] listed once.
  • "matrix": data is the n × n adjacency matrix.
  • "list": data is the adjacency list, one list per vertex.

Return the degree of every vertex.

Example 1

Input:

["edges",[[0,1],[0,2],[1,3]],4]

Output:

[2,2,1,1]

Each edge adds 1 at both ends.

Example 2

Input:

["matrix",[[0,1,1,0],[1,0,0,1],[1,0,0,0],[0,1,0,0]],4]

Output:

[2,2,1,1]

The degree is the sum of a row.

Example 3

Input:

["list",[[1,2],[0,3],[0],[1]],4]

Output:

[2,2,1,1]

The degree is the length of a list.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ number of edges ≤ 1,000
  • No self-loops and no repeated edges

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

More Adjacency matrix, adjacency list, edge list problems