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
- 59 lines of Java from the credited upstream file 2392.java.
- The implementation visibly relies on sequence storage, work queue.
- 7 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 int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {3 List<Integer> rowOrder = topologicalSort(rowConditions, k);4 if (rowOrder.isEmpty())5 return new int[][] {};6 7 List<Integer> colOrder = topologicalSort(colConditions, k);8 if (colOrder.isEmpty())9 return new int[][] {};10 11 int[][] ans = new int[k][k];12 int[] nodeToRowIndex = new int[k + 1];13 14 for (int i = 0; i < k; ++i)15 nodeToRowIndex[rowOrder.get(i)] = i;16 17 for (int j = 0; j < k; ++j) {18 final int node = colOrder[j];19 final int i = nodeToRowIndex[node];20 ans[i][j] = node;21 }22 23 return ans;24 }25 26 private List<Integer> topologicalSort(int[][] conditions, int n) {27 List<Integer> order = new ArrayList<>();28 List<Integer>[] graph = new List[n + 1];29 int[] inDegrees = new int[n + 1];30 Queue<Integer> q = new ArrayDeque<>();31 32 for (int i = 1; i <= n; ++i)33 graph[i] = new ArrayList<>();34 35 36 for (int[] condition : conditions) {37 final int u = condition[0];38 final int v = condition[1];39 graph[u].add(v);40 ++inDegrees[v];41 }42 43 44 for (int i = 1; i <= n; ++i)45 if (inDegrees[i] == 0)46 q.offer(i);47 48 while (!q.isEmpty()) {49 final int u = q.poll();50 order.add(u);51 for (final int v : graph[u])52 if (--inDegrees[v] == 0)53 q.offer(v);54 }55 56 return order.size() == n ? order : new ArrayList<>();57 }58}59