Leetcode-2392

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
#include <iostream>
#include <vector>
#include <queue>

class Solution {
    std::vector<int> tp_idx(int n, std::vector<std::vector<int>>& cond) {
        std::vector<std::vector<int>> adj(n);
        for (auto& e : cond) {
            adj[e[0] - 1].push_back(e[1] - 1);
        }
        
        std::vector<int> tpres;
        std::vector<int> inDegree(n, 0);
        for (int u = 0; u < n; ++u) {
            for (int v : adj[u]) {
                ++inDegree[v];
            }
        }
        
        std::queue<int> q;
        for (int i = 0; i < n; ++i) {
            if (inDegree[i] == 0) {
                q.push(i);
            }
        }
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            tpres.push_back(u);
            
            for (int v : adj[u]) {
                --inDegree[v];
                if (inDegree[v] == 0) {
                    q.push(v);
                }
            }
        }
        
        if (tpres.size() != n) {
            return {};
        }
        std::vector<int> res(n);
        for (int i = 0; i < n; ++i) {
            res[tpres[i]] = i;
        }
        return res;
    }
        
public:
    std::vector<std::vector<int>> buildMatrix(int k, std::vector<std::vector<int>>& rowConditions, std::vector<std::vector<int>>& colConditions) {
        std::vector<int> xs = tp_idx(k, rowConditions);
        std::vector<int> ys = tp_idx(k, colConditions);
        if (xs.size() == 0 || ys.size() == 0) {
            return {};
        }
        std::vector<std::vector<int>> res(k, std::vector<int>(k, 0));
        for (int i = 0; i < k; ++i) {
            res[xs[i]][ys[i]] = i + 1;
        }
        return res;
    }
};

Leetcode-2392