Skip to content

Commit 28e0861

Browse files
iAngkuradamant-pwn
authored andcommitted
Update topological-sort.md
The given implementation can handle most corner cases that may arise during the Topological Sort. However, it does not handle cases where the graph contains cycles (i.e., it is not a DAG). In such cases, a valid topological order does not exist. Therefore, it is necessary to check whether the graph is a DAG before applying Topological Sort.
1 parent eea0dc9 commit 28e0861

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/graph/topological-sort.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,24 @@ 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;
6364
vector<int> ans;
6465

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+
6581
void dfs(int v) {
6682
visited[v] = true;
6783
for (int u : adj[v]) {
@@ -70,17 +86,22 @@ void dfs(int v) {
7086
}
7187
ans.push_back(v);
7288
}
73-
89+
7490
void topological_sort() {
7591
visited.assign(n, false);
92+
recursion_stack.assign(n, false);
7693
ans.clear();
7794
for (int i = 0; i < n; ++i) {
78-
if (!visited[i])
95+
if (!visited[i]) {
96+
if (has_cycle(i))
97+
throw runtime_error("Graph contains cycle");
7998
dfs(i);
99+
}
80100
}
81101
reverse(ans.begin(), ans.end());
82102
}
83103
```
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.
84105
85106
The main function of the solution is `topological_sort`, which initializes DFS variables, launches DFS and receives the answer in the vector `ans`.
86107

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy