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
- 52 lines of C++ from the credited upstream file 1203.cpp.
- The implementation visibly relies on sequence storage.
- 5 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:3 vector<int> sortItems(int n, int m, vector<int>& group,4 vector<vector<int>>& beforeItems) {5 vector<vector<int>> graph(n + m);6 vector<int> inDegrees(n + m);7 8 9 for (int i = 0; i < group.size(); ++i) {10 if (group[i] == -1)11 continue;12 graph[group[i] + n].push_back(i);13 ++inDegrees[i];14 }15 16 for (int i = 0; i < beforeItems.size(); ++i)17 for (const int b : beforeItems[i]) {18 const int u = group[b] == -1 ? b : group[b] + n;19 const int v = group[i] == -1 ? i : group[i] + n;20 if (u == v) { 21 graph[b].push_back(i);22 ++inDegrees[i];23 } else {24 graph[u].push_back(v);25 ++inDegrees[v];26 }27 }28 29 30 vector<int> ans;31 32 for (int i = 0; i < n + m; ++i)33 if (inDegrees[i] == 0) 34 dfs(graph, i, inDegrees, n, ans);35 36 return ans.size() == n ? ans : vector<int>();37 }38 39 private:40 void dfs(const vector<vector<int>>& graph, int u, vector<int>& inDegrees,41 int n, vector<int>& ans) {42 if (u < n)43 ans.push_back(u);44 45 inDegrees[u] = -1; 46 47 for (const int v : graph[u])48 if (--inDegrees[v] == 0)49 dfs(graph, v, inDegrees, n, ans);50 }51};52