1. Repeated Zero In-Degree Linear Search
Intuition
Compute the in-degree of all vertices. In each of the V steps, linearly scan the vertices to find an unvisited vertex with in-degree 0. Add it to the topological ordering, mark it visited, and decrement in-degrees of all its neighbors. If no such vertex can be found before all V vertices are picked, a cycle exists.
Algorithm
- Compute
inDegreearray of size V. - Initialize
visitedarray of size V with false. - Initialize
order = []. - Loop V times:
- Find an unvisited vertex u with
inDegree[u] == 0. - If no such vertex exists, return
[](cycle detected). - Mark
visited[u] = true, append u toorder. - For each neighbor v of u, decrement
inDegree[v]. - Return
order.
#include <iostream>#include <vector> std::vector<int> topoSortBrute(int V, const std::vector<std::vector<int>>& adj) { std::vector<int> inDegree(V, 0); for (int u = 0; u < V; ++u) { for (int v : adj[u]) { inDegree[v]++; } } std::vector<bool> visited(V, false); std::vector<int> order; for (int step = 0; step < V; ++step) { int u = -1; for (int i = 0; i < V; ++i) { if (!visited[i] && inDegree[i] == 0) { u = i; break; } } if (u == -1) return {}; // Cycle detected visited[u] = true; order.push_back(u); for (int v : adj[u]) { inDegree[v]--; } } return order;} int main() { int V = 4; std::vector<std::vector<int>> adj = {{1, 2}, {3}, {3}, {}}; auto res = topoSortBrute(V, adj); std::cout << "Topo Sort (Brute): "; for (int x : res) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(V^2 + E) because in each of the V steps we linearly scan all V vertices to find an in-degree 0 vertex. - Space complexity:
O(V + E) for the adjacency list and inDegree array.