Order tasks so every prerequisite comes first. Kahn's idea: repeatedly grab whatever has no remaining dependencies (indegree 0), output it, and relax its neighbors.
Compute each node's indegree (incoming edges). Any node with indegree 0 has no unmet prerequisites, so it's safe to place next. Remove it, decrement its neighbors, repeat.
vector<int> topoSort(int n, vector<vector<int>>& adj) {
vector<int> indeg(n, 0);
for (int u = 0; u < n; u++)
for (int v : adj[u]) indeg[v]++;
queue<int> q;
for (int i = 0; i < n; i++)
if (indeg[i] == 0) q.push(i); // no prerequisites
vector<int> order;
while (!q.empty()) {
int u = q.front(); q.pop();
order.push_back(u);
for (int v : adj[u])
if (--indeg[v] == 0) q.push(v); // now unblocked
}
if (order.size() != n) return {}; // cycle → no valid order
return order;
}
One pass to build indegrees, one pass processing each node and edge.
Indegree array plus the queue and output order.
If fewer than V nodes come out, some were stuck in a cycle.