Represent the Network

You are given the number of vertices n (labeled from 0 to n-1) and a 2D array edges representing the directed edges of a simple directed graph. Construct and print its adjacency matrix followed by its adjacency lists.

Output Constraints:

  1. Adjacency Matrix: Print the n x n matrix row by row. Each element should be separated by a single space. Do not leave any trailing space at the end of a line.
  2. Adjacency List: Immediately after the matrix, print the adjacency lists for each vertex from 0 to n-1. The format should be vertex: neighbor_1 neighbor_2 .... The neighbors must be printed in increasing order and separated by a single space. Do not leave any trailing space at the end of a line. If a vertex has no outgoing edges, print just vertex: with no trailing space.

Example 1:

Input:

n = 3
edges = [[0, 1], [0, 2], [1, 2]]

Output:

0 1 1
0 0 1
0 0 0
0: 1 2
1: 2
2:

Explanation:

The graph has 3 vertices. There are directed edges from 0 to 1, 0 to 2, and 1 to 2.

The adjacency matrix reflects these edges with 1s.

The adjacency list shows the neighbors of 0 in increasing order (1 and 2). Vertex 2 has no outgoing edges, so it is just printed as 2:.

Example 2:

Input:

n = 4
edges = [[2, 0], [1, 3], [2, 3], [0, 1]]

Output:

0 1 0 0
0 0 0 1
1 0 0 1
0 0 0 0
0: 1
1: 3
2: 0 3
3:

Explanation:

The matrix correctly places a 1 at (0,1), (1,3), (2,0), and (2,3).

In the adjacency list, vertex 2 connects to 0 and 3. They are printed in increasing order as 0 3. Vertex 3 has no outgoing edges.

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 500
  • 0 <= edges.length <= n * (n - 1)
  • edges[i].length == 2
  • 0 <= edges[i][0], edges[i][1] < n
  • edges[i][0] != edges[i][1] (No self-loops)
  • There are no duplicate edges in the given list (The graph is a simple directed graph).

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
void constructGraph(int n, vector<vector<int>>& edges) {
// Write your code here
}
};
Test Case

Input:

Edges
N