2392. Build a Matrix With Conditions
Problem
Build a k×k matrix containing each number 1…k exactly once (the remaining cells are 0) such that for every [above, below] in rowConditions, above is in a strictly higher row than below, and for every [left, right] in colConditions, left is in a strictly earlier column than right. Return any such matrix, or an empty matrix if none exists.
Example: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] → [[3,0,0],[0,0,1],[0,2,0]] (one valid answer)
Constraints: k ≤ 400.
Rows and columns are independent. Topologically sort the numbers 1..k by rowConditions (gives each number's row) and separately by colConditions (its column); a cycle in either means no answer. Place number v at (row[v], col[v]) — every row and column gets exactly one number. Any valid matrix is accepted.
Complexity: O(k² + conditions) (the k × k output dominates).
class Solution:
def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
def topo(conds):
adj, indeg = defaultdict(list), [0] * (k + 1)
for a, b in conds:
adj[a].append(b)
indeg[b] += 1
q = deque(v for v in range(1, k + 1) if indeg[v] == 0)
order = []
while q:
v = q.popleft()
order.append(v)
for w in adj[v]:
indeg[w] -= 1
if indeg[w] == 0:
q.append(w)
return {v: i for i, v in enumerate(order)} if len(order) == k else None
row, col = topo(rowConditions), topo(colConditions)
if row is None or col is None:
return []
m = [[0] * k for _ in range(k)]
for v in range(1, k + 1):
m[row[v]][col[v]] = v
return m
def valid(k, rc, cc, m): # any matrix satisfying the conditions is accepted
pos = {m[i][j]: (i, j) for i in range(k) for j in range(k) if m[i][j]}
return (len(m) == k and all(len(r) == k for r in m) and sorted(pos) == list(range(1, k + 1))
and all(pos[a][0] < pos[b][0] for a, b in rc) and all(pos[a][1] < pos[b][1] for a, b in cc))
assert valid(3, [[1, 2], [3, 2]], [[2, 1], [3, 2]], Solution().buildMatrix(3, [[1, 2], [3, 2]], [[2, 1], [3, 2]]))
assert Solution().buildMatrix(3, [[1, 2], [2, 3], [3, 1], [2, 3]], [[2, 1]]) == []
assert valid(4, [[4, 3], [3, 2], [2, 1]], [[1, 2], [2, 3]], Solution().buildMatrix(4, [[4, 3], [3, 2], [2, 1]], [[1, 2], [2, 3]]))
class Solution {
public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
int[] row = topo(k, rowConditions), col = topo(k, colConditions);
if (row == null || col == null) return new int[0][0];
int[][] m = new int[k][k];
for (int v = 1; v <= k; v++) m[row[v]][col[v]] = v;
return m;
}
private int[] topo(int k, int[][] conds) { // position of each value, or null on a cycle
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= k; i++) adj.add(new ArrayList<>());
int[] indeg = new int[k + 1], pos = new int[k + 1];
for (int[] c : conds) { adj.get(c[0]).add(c[1]); indeg[c[1]]++; }
Deque<Integer> q = new ArrayDeque<>();
for (int v = 1; v <= k; v++) if (indeg[v] == 0) q.add(v);
int idx = 0;
while (!q.isEmpty()) {
int v = q.poll();
pos[v] = idx++;
for (int w : adj.get(v)) if (--indeg[w] == 0) q.add(w);
}
return idx == k ? pos : null;
}
}
func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int {
topo := func(conds [][]int) []int { // pos[v] = v's place in a topological order; nil on a cycle
adj := make([][]int, k+1)
indeg := make([]int, k+1)
for _, c := range conds {
adj[c[0]] = append(adj[c[0]], c[1])
indeg[c[1]]++
}
q := []int{}
for v := 1; v <= k; v++ {
if indeg[v] == 0 {
q = append(q, v)
}
}
pos := make([]int, k+1)
placed := 0
for len(q) > 0 {
v := q[0]
q = q[1:]
pos[v] = placed
placed++
for _, w := range adj[v] {
indeg[w]--
if indeg[w] == 0 {
q = append(q, w)
}
}
}
if placed < k {
return nil
}
return pos
}
row, col := topo(rowConditions), topo(colConditions)
if row == nil || col == nil {
return [][]int{}
}
m := make([][]int, k)
for i := range m {
m[i] = make([]int, k)
}
for v := 1; v <= k; v++ {
m[row[v]][col[v]] = v
}
return m
}