Problem: Build a Matrix With Conditions

You are given a positive integer `k`. You are also given:

* a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and
* a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`.

The two arrays contain integers from `1` to `k`.

You have to build a `k x k` matrix that contains each of the numbers from `1`
to `k` exactly once. The remaining cells should have the value `0`.

The matrix should also satisfy the following conditions:

* The number `abovei` should appear in a row that is strictly above the row at which the number `belowi` appears for all `i` from `0` to `n - 1`.
* The number `lefti` should appear in a column that is strictly left of the column at which the number `righti` appears for all `i` from `0` to `m - 1`.

Return any matrix that satisfies the conditions. If no answer exists, return
an empty matrix.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
    rowOrder = self._topologicalSort(rowConditions, k)
    if not rowOrder:
      return []

    colOrder = self._topologicalSort(colConditions, k)
    if not colOrder:
      return []

    ans = [[0] * k for _ in range(k)]
    nodeToRowIndex = [0] * (k + 1)

    for i, node in enumerate(rowOrder):
      nodeToRowIndex[node] = i

    for j, node in enumerate(colOrder):
      i = nodeToRowIndex[node]
      ans[i][j] = node

    return ans

  def _topologicalSort(self, conditions: List[List[int]], n: int) -> List[int]:
    order = []
    graph = [[] for _ in range(n + 1)]
    inDegrees = [0] * (n + 1)

    for u, v in conditions:
      graph[u].append(v)
      inDegrees[v] += 1

    q = collections.deque([i for i in range(1, n + 1) if inDegrees[i] == 0])

    while q:
      u = q.popleft()
      order.append(u)
      for v in graph[u]:
        inDegrees[v] -= 1
        if inDegrees[v] == 0:
          q.append(v)

    if len(order) == n:
      return order
    else:
      return []


Java solution:
class Solution {
  public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
    List<Integer> rowOrder = topologicalSort(rowConditions, k);
    if (rowOrder.isEmpty())
      return new int[][] {};

    List<Integer> colOrder = topologicalSort(colConditions, k);
    if (colOrder.isEmpty())
      return new int[][] {};

    int[][] ans = new int[k][k];
    int[] nodeToRowIndex = new int[k + 1];

    for (int i = 0; i < k; ++i)
      nodeToRowIndex[rowOrder.get(i)] = i;

    for (int j = 0; j < k; ++j) {
      final int node = colOrder.get(j);
      final int i = nodeToRowIndex[node];
      ans[i][j] = node;
    }

    return ans;
  }

  private List<Integer> topologicalSort(int[][] conditions, int n) {
    List<Integer> order = new ArrayList<>();
    List<Integer>[] graph = new List[n + 1];
    int[] inDegrees = new int[n + 1];
    Queue<Integer> q = new ArrayDeque<>();

    for (int i = 1; i <= n; ++i)
      graph[i] = new ArrayList<>();

    // Build the graph.
    for (int[] condition : conditions) {
      final int u = condition[0];
      final int v = condition[1];
      graph[u].add(v);
      ++inDegrees[v];
    }

    // Perform topological sorting.
    for (int i = 1; i <= n; ++i)
      if (inDegrees[i] == 0)
        q.offer(i);

    while (!q.isEmpty()) {
      final int u = q.poll();
      order.add(u);
      for (final int v : graph[u])
        if (--inDegrees[v] == 0)
          q.offer(v);
    }

    return order.size() == n ? order : new ArrayList<>();
  }
}


C++ solution:
class Solution {
 public:
  vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions,
                                  vector<vector<int>>& colConditions) {
    const vector<int> rowOrder = topologicalSort(rowConditions, k);
    if (rowOrder.empty())
      return {};

    const vector<int> colOrder = topologicalSort(colConditions, k);
    if (colOrder.empty())
      return {};

    vector<vector<int>> ans(k, vector<int>(k));
    vector<int> nodeToRowIndex(k + 1);

    for (int i = 0; i < k; ++i)
      nodeToRowIndex[rowOrder[i]] = i;

    for (int j = 0; j < k; ++j) {
      const int node = colOrder[j];
      const int i = nodeToRowIndex[node];
      ans[i][j] = node;
    }

    return ans;
  }

 private:
  vector<int> topologicalSort(const vector<vector<int>>& conditions, int n) {
    vector<int> order;
    vector<vector<int>> graph(n + 1);
    vector<int> inDegrees(n + 1);
    queue<int> q;

    // Build the graph.
    for (const vector<int>& condition : conditions) {
      const int u = condition[0];
      const int v = condition[1];
      graph[u].push_back(v);
      ++inDegrees[v];
    }

    // Perform topological sorting.
    for (int i = 1; i <= n; ++i)
      if (inDegrees[i] == 0)
        q.push(i);

    while (!q.empty()) {
      const int u = q.front();
      q.pop();
      order.push_back(u);
      for (const int v : graph[u])
        if (--inDegrees[v] == 0)
          q.push(v);
    }

    return order.size() == n ? order : vector<int>();
  }
};