← Back to problems
UNSW COMP2521 · easy

Graph: Build the Adjacency Matrix

Graph: read undirected edges into an adjacency matrix

Read an undirected graph: vertices 0 … V-1, with E edges. Store it in a V×V adjacency matrix and print it.

Complete the edge-reading loop body: for each undirected edge u–v, set both adj[u][v] and adj[v][u] to 1.

Pitfall (straight from the bug lab): an undirected edge has no direction, u–v equals v–u, so both symmetric cells must be set. Setting only one direction hides the edge from the other endpoint and breaks traversals and degree counts later. This is the most common graph bug.

Input

  • Line 1: V E (vertex count, edge count).
  • Next E lines: u v, an undirected edge (E may be 0).

Output

  • V lines, each with V numbers (0 or 1), a space after each — the whole adjacency matrix.

Example: input 4 3 / 0 1 / 0 2 / 2 3 -> row 0 is 0 1 1 0 (vertex 0 connects to 1 and 2).