2392. Build a Matrix With Conditions (21 July 2024)
Problem Description
Given a positive integer k, along with:
- A 2D integer array
rowConditionsof sizenwhererowConditions[i] = [above_i, below_i], and - A 2D integer array
colConditionsof sizemwherecolConditions[i] = [left_i, right_i].
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, satisfying the following conditions:
- The number
above_ishould appear in a row strictly above the row at which the numberbelow_iappears for allifrom 0 ton - 1. - The number
left_ishould appear in a column strictly left of the column at which the numberright_iappears for allifrom 0 tom - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
You can find the problem statement on LeetCode.
Solution Explanation
To solve this problem, we need to construct a matrix such that it satisfies the given row and column conditions. Here's a step-by-step explanation of how we can achieve this:
1. Create Adjacency Lists and Indegree Arrays
- We create adjacency lists and indegree arrays for both row and column conditions.
2. Perform Topological Sorting
- Use Kahn's algorithm to perform topological sorting on the row and column graphs to get the order of numbers.
3. Check for Cycles
- If a cycle is detected in either the row or column graph, return an empty matrix as it's impossible to satisfy the conditions.
4. Place Numbers in the Matrix
- Use the sorted orders to place numbers in the matrix ensuring all conditions are met.
Here's the C++ code implementing this solution:
class Solution {
public:
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
// Create adjacency lists and indegree arrays for row and column conditions
vector<vector<int>> rowAdj(k + 1), colAdj(k + 1);
vector<int> rowIndegree(k + 1, 0), colIndegree(k + 1, 0);
for (auto& rc : rowConditions) {
rowAdj[rc[0]].push_back(rc[1]);
rowIndegree[rc[1]]++;
}
for (auto& cc : colConditions) {
colAdj[cc[0]].push_back(cc[1]);
colIndegree[cc[1]]++;
}
// Perform topological sorting
auto topoSort = [&](vector<vector<int>>& adj, vector<int>& indegree) {
vector<int> order;
queue<int> q;
for (int i = 1; i <= k; ++i) {
if (indegree[i] == 0) q.push(i);
}
while (!q.empty()) {
int node = q.front();
q.pop();
order.push_back(node);
for (int neighbor : adj[node]) {
if (--indegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
// Check if the topological sort is possible
if (order.size() != k) return vector<int>(); // Cycle detected
return order;
};
vector<int> rowOrder = topoSort(rowAdj, rowIndegree);
vector<int> colOrder = topoSort(colAdj, colIndegree);
if (rowOrder.empty() || colOrder.empty()) return {}; // If there's a cycle in either sort, return empty matrix
// Build the position maps
vector<int> rowPos(k + 1), colPos(k + 1);
for (int i = 0; i < k; ++i) {
rowPos[rowOrder[i]] = i;
colPos[colOrder[i]] = i;
}
// Build the matrix
vector<vector<int>> matrix(k, vector<int>(k, 0));
for (int i = 1; i <= k; ++i) {
matrix[rowPos[i]][colPos[i]] = i;
}
return matrix;
}
};Initialization and Graph Construction
-
Adjacency Lists (
rowAdjandcolAdj):- Represent the directed graphs for row and column constraints, where each list records directional relationships.
-
Indegree Arrays (
rowIndegreeandcolIndegree):- Count the number of incoming edges for each node (or matrix index), which are critical for determining the starting points for topological sorting.
Topological Sorting Function
- Kahn's Algorithm:
- Processes nodes with zero indegree, dequeuing them, processing, and subsequently removing them from the graph, which decreases the indegree of their successors.
- If all nodes are processed without inconsistencies, the conditions are satisfiable. If any node remains with a non-zero indegree, it indicates unsatisfiable conditions due to cycles.
Example of Topological Sorting
Consider a scenario with three tasks where:
- Task 3 must be completed before Task 1.
- Task 2 must be completed before Task 3.
The adjacency list and indegree array would look like this:
- Adjacency List:
{2: [3], 3: [1]} - Indegree Array:
{1: 1, 2: 0, 3: 1}
Processing steps using Kahn's algorithm:
- Start with Task 2 (indegree of 0), place it in the sorted order.
- Remove Task 2, decrease the indegree of Task 3 to 0, and enqueue it.
- Process Task 3 next, followed by Task 1 as its indegree becomes 0.
Resulting topological order: [2, 3, 1]
Constructing the Matrix
-
Position Maps:
- Use topological sorting results to map each number to its position in the final matrix, ensuring rows and columns are placed as dictated by the sort.
-
Matrix Construction:
- Fill the matrix using the established position maps, ensuring that the matrix layout respects the sorted order and conditions.
Conclusion
The described method leverages graph theory and topological sorting to efficiently and effectively construct a matrix that satisfies specific row and column conditions or indicates the impossibility of such a matrix through detection of cycles. This approach showcases the practical application of these concepts in solving complex ordering problems.