-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuild a Matrix With Conditions
75 lines (61 loc) Β· 2.17 KB
/
Build a Matrix With Conditions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Solution {
private:
vector<int> topologicalSort(int k, vector<vector<int>>& conditions) {
vector<vector<int>> graph(k + 1);
vector<int> inDegree(k + 1, 0);
vector<bool> seen(k + 1, false);
for (const auto& condition : conditions) {
graph[condition[0]].push_back(condition[1]);
inDegree[condition[1]]++;
seen[condition[0]] = seen[condition[1]] = true;
}
queue<int> q;
vector<int> order;
for (int i = 1; i <= k; i++) {
if (inDegree[i] == 0) {
q.push(i);
if (!seen[i]) order.push_back(i);
}
}
while (!q.empty()) {
int node = q.front();
q.pop();
if (seen[node]) order.push_back(node);
for (int neighbor : graph[node]) {
if (--inDegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
for (int i = 1; i <= k; i++) {
if (inDegree[i] > 0) return {};
}
while (order.size() < k) {
for (int i = 1; i <= k; i++) {
if (find(order.begin(), order.end(), i) == order.end()) {
order.push_back(i);
break;
}
}
}
return order;
}
public:
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
vector<int> rowOrder = topologicalSort(k, rowConditions);
vector<int> colOrder = topologicalSort(k, colConditions);
if (rowOrder.empty() || colOrder.empty()) {
return {};
}
vector<vector<int>> result(k, vector<int>(k, 0));
vector<int> rowPosition(k + 1), colPosition(k + 1);
for (int i = 0; i < k; i++) {
rowPosition[rowOrder[i]] = i;
colPosition[colOrder[i]] = i;
}
for (int num = 1; num <= k; num++) {
result[rowPosition[num]][colPosition[num]] = num;
}
return result;
}
};