Approach
Breadth-first search
For Build a Matrix With Conditions, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 60 lines of C++ from the credited upstream file 2392.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions,4 vector<vector<int>>& colConditions) {5 const vector<int> rowOrder = topologicalSort(rowConditions, k);6 if (rowOrder.empty())7 return {};8 9 const vector<int> colOrder = topologicalSort(colConditions, k);10 if (colOrder.empty())11 return {};12 13 vector<vector<int>> ans(k, vector<int>(k));14 vector<int> nodeToRowIndex(k + 1);15 16 for (int i = 0; i < k; ++i)17 nodeToRowIndex[rowOrder[i]] = i;18 19 for (int j = 0; j < k; ++j) {20 const int node = colOrder[j];21 const int i = nodeToRowIndex[node];22 ans[i][j] = node;23 }24 25 return ans;26 }27 28 private:29 vector<int> topologicalSort(const vector<vector<int>>& conditions, int n) {30 vector<int> order;31 vector<vector<int>> graph(n + 1);32 vector<int> inDegrees(n + 1);33 queue<int> q;34 35 36 for (const vector<int>& condition : conditions) {37 const int u = condition[0];38 const int v = condition[1];39 graph[u].push_back(v);40 ++inDegrees[v];41 }42 43 44 for (int i = 1; i <= n; ++i)45 if (inDegrees[i] == 0)46 q.push(i);47 48 while (!q.empty()) {49 const int u = q.front();50 q.pop();51 order.push_back(u);52 for (const int v : graph[u])53 if (--inDegrees[v] == 0)54 q.push(v);55 }56 57 return order.size() == n ? order : vector<int>();58 }59};60