How do I find a cycle in a directed graph using topological sort? -
i have implemented pseudocode in programme check if directed graph acyclic:
l ← empty list contain sorted elements s ← set of nodes no incoming edges while s non-empty remove node n s add together n tail of l each node m border e n m remove border e graph if m has no other incoming edges insert m s if graph has edges homecoming error (graph has @ to the lowest degree 1 cycle) else homecoming l (a topologically sorted order)
this works great, need output actual cycle if graph isn't acyclic. possible "inside" code, or need alter algorithm completely? have tried search solution, , found reply (printing(not detecting) cycle topological sort) can't understand how this. have pseudocode help me?
first of all, you're trying bit problematic, since there may more 1 cycle. theoretically, every node in graph have self pointing edge, there'll n cycles.
however, easy approach grab border in graph, iterate on until reach same edge, , output cycle. edges result in dead-ends should removed, , cycle found should remove cycle edges graph well. maintain doing until graph has no more edges , should output cycles in graph, albeit in no particular order or optimisation, , may miss cycles if performed in order.
cycle directed-acyclic-graphs topological-sort
No comments:
Post a Comment