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
- 46 lines of Python from the credited upstream file 2392.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit 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 def buildMatrix(self, k: int, rowConditions: list[list[int]],3 colConditions: list[list[int]]) -> list[list[int]]:4 rowOrder = self._topologicalSort(rowConditions, k)5 if not rowOrder:6 return []7 8 colOrder = self._topologicalSort(colConditions, k)9 if not colOrder:10 return []11 12 ans = [[0] * k for _ in range(k)]13 nodeToRowIndex = [0] * (k + 1)14 15 for i, node in enumerate(rowOrder):16 nodeToRowIndex[node] = i17 18 for j, node in enumerate(colOrder):19 i = nodeToRowIndex[node]20 ans[i][j] = node21 22 return ans23 24 def _topologicalSort(self, conditions: list[list[int]], n: int) -> list[int]:25 order = []26 graph = [[] for _ in range(n + 1)]27 inDegrees = [0] * (n + 1)28 29 30 for u, v in conditions:31 graph[u].append(v)32 inDegrees[v] += 133 34 35 q = collections.deque([i for i in range(1, n + 1) if inDegrees[i] == 0])36 37 while q:38 u = q.popleft()39 order.append(u)40 for v in graph[u]:41 inDegrees[v] -= 142 if inDegrees[v] == 0:43 q.append(v)44 45 return order if len(order) == n else []46