Problem Description
Given a positive integer k and two lists of order conditions (one for rows and one for columns), build a k x k matrix where each of the numbers from 1 to k appears exactly once (all other cells remain 0). The rowConditions list specifies that one number must appear in a row strictly above another number, and the colConditions list specifies a similar constraint for columns. Return any valid matrix that satisfies these conditions, or return an empty matrix if none exists.
Key Insights
- The order constraints for rows and columns can be modeled as separate directed graphs.
- Topological sorting (using Kahn’s algorithm) is used to determine a valid ordering that obeys the given conditions.
- Two independent topological sorts are performed: one for row ordering and one for column ordering.
- Once valid orderings are obtained, use their positions to place each number in the matrix, where the row index is given by the row order and the column index by the column order.
- If either ordering fails (i.e. there is a cycle), then no valid matrix exists and an empty matrix should be returned.
Space and Time Complexity
Time Complexity: O(k + R + C) where R is the number of rowConditions and C is the number of colConditions.
Space Complexity: O(k + R + C) for storing graphs, in-degrees, and the ordering arrays.
Solution
We first build two directed graphs for the row and column conditions. For each graph, we perform a topological sort using Kahn's algorithm, which involves:
- Building an adjacency list and maintaining an in-degree count for each node (number).
- Using a queue to process nodes whose in-degree is zero.
If the sorted order does not include all nodes, then a cycle exists and no valid ordering is possible.
After obtaining valid orderings, we create a mapping from number to its position in the ordering for both rows and columns. Then, we iterate through each number and place it in the matrix at the position determined by these mappings.
The final matrix is returned if both orderings are valid; otherwise, an empty matrix is returned.