Approach
Depth-first search
For Sort Items by Groups Respecting Dependencies, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 51 lines of Java from the credited upstream file 1203.java.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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[] sortItems(int n, int m, int[] group, List<List<Integer>> beforeItems) {3 List<Integer>[] graph = new List[n + m];4 int[] inDegrees = new int[n + m];5 6 for (int i = 0; i < graph.length; ++i)7 graph[i] = new ArrayList<>();8 9 10 for (int i = 0; i < group.length; ++i) {11 if (group[i] == -1)12 continue;13 graph[group[i] + n].add(i);14 ++inDegrees[i];15 }16 17 for (int i = 0; i < beforeItems.size(); ++i)18 for (final int b : beforeItems.get(i)) {19 final int u = group[b] == -1 ? b : group[b] + n;20 final int v = group[i] == -1 ? i : group[i] + n;21 if (u == v) { 22 graph[b].add(i);23 ++inDegrees[i];24 } else {25 graph[u].add(v);26 ++inDegrees[v];27 }28 }29 30 31 List<Integer> ans = new ArrayList<>();32 33 for (int i = 0; i < n + m; ++i)34 if (inDegrees[i] == 0) 35 dfs(graph, i, inDegrees, n, ans);36 37 return ans.size() == n ? ans.stream().mapToInt(Integer::intValue).toArray() : new int[] {};38 }39 40 private void dfs(List<Integer>[] graph, int u, int[] inDegrees, int n, List<Integer> ans) {41 if (u < n)42 ans.add(u);43 44 inDegrees[u] = -1; 45 46 for (final int v : graph[u])47 if (--inDegrees[v] == 0)48 dfs(graph, v, inDegrees, n, ans);49 }50}51