Skip to content

Commit 72af70d

Browse files
committed
provide better clarification on what happens with non-acyclic graphs
1 parent 28e0861 commit 72af70d

File tree

1 file changed

+1
-20
lines changed

1 file changed

+1
-20
lines changed

src/graph/topological-sort.md

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -60,24 +60,8 @@ Here is an implementation which assumes that the graph is acyclic, i.e. the desi
6060
int n; // number of vertices
6161
vector<vector<int>> adj; // adjacency list of graph
6262
vector<bool> visited;
63-
vector<bool> recursion_stack;
6463
vector<int> ans;
6564

66-
bool has_cycle(int v) {
67-
visited[v] = true;
68-
recursion_stack[v] = true;
69-
for (int u : adj[v]) {
70-
if (!visited[u]) {
71-
if (has_cycle(u))
72-
return true;
73-
}
74-
else if (recursion_stack[u])
75-
return true;
76-
}
77-
recursion_stack[v] = false;
78-
return false;
79-
}
80-
8165
void dfs(int v) {
8266
visited[v] = true;
8367
for (int u : adj[v]) {
@@ -93,17 +77,14 @@ void topological_sort() {
9377
ans.clear();
9478
for (int i = 0; i < n; ++i) {
9579
if (!visited[i]) {
96-
if (has_cycle(i))
97-
throw runtime_error("Graph contains cycle");
9880
dfs(i);
9981
}
10082
}
10183
reverse(ans.begin(), ans.end());
10284
}
10385
```
104-
This implementation uses an additional `recursion_stack` array to keep track of vertices in the current DFS path. If a visited vertex is found again in the recursion stack, then it means a cycle exists in the graph, and the function throws a runtime error.
10586
106-
The main function of the solution is `topological_sort`, which initializes DFS variables, launches DFS and receives the answer in the vector `ans`.
87+
The main function of the solution is `topological_sort`, which initializes DFS variables, launches DFS and receives the answer in the vector `ans`. It is worth noting that when the graph is not acyclic, `topological_sort` result would still be somewhat meaningful in a sense that if a vertex $u$ is reachable from vertex $v$, but not vice versa, the vertex $v$ will always come first in the resulting array. This property of the provided implementation is used in [Kosaraju's algorithm](./strongly-connected-components.md) to extract strongly connected components and their topological sorting in a directed graph with cycles.
10788
10889
## Practice Problems
10990

0 commit comments

Comments
 (0)