Sign in

Build an Adjacency Matrix

intro

Represent a directed graph on nodes 0 through n-1 as an adjacency matrix. Implement build_mat(n, edges) returning an n x n matrix of 0/1 values where mat[u][v] == 1 exactly when at least one directed edge u -> v exists. The graph is directed: an edge u -> v sets only mat[u][v], never mat[v][u], unless a separate edge v -> u is also given. A self-loop (u, u) sets mat[u][u] = 1. Parallel edges u -> v given more than once still leave mat[u][v] at 1; do not count multiplicities.

Example: build_mat(3, {(0,1), (1,2), (0,0)}) returns {{1,1,0}, {0,0,1}, {0,0,0}}: row 0 has a 1 at column 1 (edge 0->1) and at column 0 (the self-loop), row 1 has a 1 at column 2 (edge 1->2), row 2 is all zero (no outgoing edges from node 2).

Input format: each test in tests/*.in is laid out as:

  • Line 1: n e, the node count and the number of directed edges; nodes are numbered 0 to n - 1.
  • Next e lines: u v, one directed edge from u to v. When e is 0 the file is just the header line.

Test 04.in reads:

1 0

This is a single node with no edges at all. The header is the entire test; build_mat still has to return a 1 x 1 matrix of zeros.

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...