Which cycle detection within a directed graph are more efficient than O(n^2)? [closed]
Tarjan’s strongly connected components algorithm has O(|E| + |V|) time complexity. For other algorithms, see Strongly connected components on Wikipedia.
Tarjan’s strongly connected components algorithm has O(|E| + |V|) time complexity. For other algorithms, see Strongly connected components on Wikipedia.
Graph# is also another option. I haven’t used it personally, but I’ve been meaning to get around to looking over it.
The above is actually correct, I did not understand what a strongly connected component was. I was expecting the function to return an empty List of strongly connected components, yet it was returning a list of single nodes. I believe the above is working. Feel free to use if you need it!
If by having “one root element” you mean your directed graph is a rooted tree, then the root will be the only node with zero in-degree. You can find that node in linear time (in the number of nodes) with: In [1]: import networkx as nx In [2]: G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted at 0 In … Read more
If I understood your question correctly, then a new edge (u,v) is only inserted if there was no path from v to u before (i.e., if (u,v) does not create a cycle). Thus, your graph is always a DAG (directed acyclic graph). Using Tarjan’s Algorithm to detect strongly connected components (http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm) sounds like an overkill … Read more
Topological Sort (From Wikipedia): In graph theory, a topological sort or topological ordering of a directed acyclic graph (DAG) is a linear ordering of its nodes in which each node comes before all nodes to which it has outbound edges. Every DAG has one or more topological sorts. Pseudo code: L ← Empty list where … Read more
I would try to sort the graph topologically, and if you can’t, then it has cycles.
Fully fleshed out example with arrows for only the red edges: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from( [(‘A’, ‘B’), (‘A’, ‘C’), (‘D’, ‘B’), (‘E’, ‘C’), (‘E’, ‘F’), (‘B’, ‘H’), (‘B’, ‘G’), (‘B’, ‘F’), (‘C’, ‘G’)]) val_map = {‘A’: 1.0, ‘D’: 0.5714285714285714, ‘H’: 0.0} values = [val_map.get(node, 0.25) for node … Read more
The DOT user manual gives the following example of a graph with clusters with edges between clusters: IMPORTANT: The initial compound=true statement is required. digraph G { compound=true; subgraph cluster0 { a -> b; a -> c; b -> d; c -> d; } subgraph cluster1 { e -> g; e -> f; } b … Read more
Tarjan’s strongly connected components algorithm has O(|E| + |V|) time complexity. For other algorithms, see Strongly connected components on Wikipedia.