-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
build-a-matrix-with-conditions.cpp
62 lines (60 loc) · 1.97 KB
/
build-a-matrix-with-conditions.cpp
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
// Time: O(k^2 + r + c), r = len(rowConditions), c = len(colConditions)
// Space: O(k + r + c)
// topological sort
class Solution {
public:
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
const auto& topological_sort = [&](const auto& conditions) {
vector<vector<int>> adj(k);
vector<int> in_degree(k);
for (const auto& c : conditions) {
const int u = c[0] - 1, v = c[1] - 1;
adj[u].emplace_back(v);
++in_degree[v];
}
vector<int> result;
vector<int> q;
for (int u = 0; u < k; ++u) {
if (!in_degree[u]) {
q.emplace_back(u);
}
}
while (!empty(q)) {
vector<int> new_q;
for (const auto& u : q) {
result.emplace_back(u);
for (const auto& v : adj[u]) {
--in_degree[v];
if (in_degree[v]) {
continue;
}
new_q.emplace_back(v);
}
}
q = move(new_q);
}
return result;
};
const auto& row_order = topological_sort(rowConditions);
if (size(row_order) != k) {
return {};
}
const auto& col_order = topological_sort(colConditions);
if (size(col_order) != k) {
return {};
}
vector<int> row_idx(k);
for (int i = 0; i < k; ++i) {
row_idx[row_order[i]] = i;
}
vector<int> col_idx(k);
for (int i = 0; i < k; ++i) {
col_idx[col_order[i]] = i;
}
vector<vector<int>> result(k, vector<int>(k));
for (int i = 0; i < k; ++i) {
result[row_idx[i]][col_idx[i]] = i + 1;
}
return result;
}
};