Skip to contentKEEP THE CRAFTTHE SANCTUARY

Build Graph Representations

Turn an undirected edge list into a sorted adjacency list and an adjacency matrix.

The problem

Implement build_graph_representations(node_count, edges). The nodes are numbered 0 to node_count - 1, and each edge [u, v] is undirected. Return [adjacency_list, adjacency_matrix]. adjacency_list[i] is the list of i's neighbors in increasing order. adjacency_matrix is a node_count x node_count grid where adjacency_matrix[i][j] is 1 when i and j are connected and 0 otherwise. The same edge can appear more than once, in either direction; count it once. A self-loop [v, v] makes v its own neighbor, listed once. Nodes with no edges still get an empty list and a row of zeros.

Starter code

def build_graph_representations(node_count, edges):
    pass

Public examples

  1. node_count = 3, edges = [[0, 1], [1, 2]]gives[[[1], [0, 2], [1]], [[0, 1, 0], [1, 0, 1], [0, 1, 0]]]
  2. node_count = 2, edges = [[0, 1], [1, 0], [1, 1]]gives[[[1], [0, 1]], [[0, 1], [1, 1]]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.