Hassle Free Method and Easy to Understand
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(k*^2 + n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(k*^2 + n)\n\n# Code\n```\nclass Solution {\npublic:\n\n      vector<int> topoSort(vector<vector<int>>& edges, int n) {\n        unordered_map<int, vector<int>> adj;\n        stack<int> st;\n        vector<int> order;\n        //0 : not visited;\n        //1 : visiting (currently in stack via some other DFS)\n        //2 : visited\n        vector<int> visited(n + 1, 0);\n        bool hasCycle = false;\n\n        for (vector<int>& edge : edges) {\n            int u = edge[0];\n            int v = edge[1];\n            adj[u].push_back(v);\n        }\n\n        for (int i = 1; i <= n; i++) {\n            if (visited[i] == 0) {\n                dfs(i, adj, visited, st, hasCycle);\n                if (hasCycle) \n                    return {}; //no ordering possible\n            }\n        }\n        \n        while(!st.empty()) {\n            order.push_back(st.top());\n            st.pop();\n        }\n        return order;\n    }\n\n    void dfs(int node, unordered_map<int, vector<int>>& adj, vector<int>& visited,\n             stack<int>& st, bool& hasCycle) {\n        \n        visited[node] = 1;  // Mark node as visiting\n        //First, visit node\'s children\n        for (int& nbr : adj[node]) {\n            if (visited[nbr] == 0) {\n                dfs(nbr, adj, visited, st, hasCycle);\n            } else if (visited[nbr] == 1) {\n                // Cycle detected\n                hasCycle = true;\n                return;\n            }\n        }\n\n        visited[node] = 2; //visited\n        st.push(node); //Now node can be added\n    }\n\n    vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions,\n                                    vector<vector<int>>& colConditions) {        \n        vector<int> orderRows    = topoSort(rowConditions, k);\n        vector<int> orderColumns = topoSort(colConditions, k);\n\n        // We might have found cycle. That\'s why topo order is empty\n        if (orderRows.empty() or orderColumns.empty())\n            return {};\n\n        vector<vector<int>> matrix(k, vector<int>(k, 0));\n        for (int i = 0; i < k; i++) {\n            for (int j = 0; j < k; j++) {\n                if (orderRows[i] == orderColumns[j]) {\n                    matrix[i][j] = orderRows[i];\n                }\n            }\n        }\n        return matrix;\n    }\n};\n```
['Graph', 'Topological Sort', 'Matrix', 'C++']