Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to represent graphs /trees in python and how to detect cycles?

i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ?

like image 392
Bunny Rabbit Avatar asked Dec 14 '10 20:12

Bunny Rabbit


People also ask

How do you determine the cycle of a tree?

To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack then there is a cycle in the tree.

How do you know how many cycles a graph has?

The maximum number of independent cycles in a graph (u) is estimated through the number of nodes (v), links (e) and of sub-graphs (p). Trees and simple networks have a value of 0 since they have no cycles.

How can a program detect cycles in a directed graph explain?

To detect a cycle in a directed graph, we can either use the Depth First Search or the Breadth First Search approach. In the DFS technique, we check if there exists a back edge in the DFS tree of the graph because the existence of the back edge indicates the presence of a cycle.


2 Answers

The simplest way of representing it (in my opinion) is by using a dict of arrays lists:

graph = {}
graph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]

A simple way of finding cycles is by using a BF or DF search:

def df(node):
    if visited(node):
        pass # found a cycle here, do something with it
    visit(node)
    [df(node_id) for node_id in graph[node]]

Disclaimer: this is actually a sketch; neighbors(), visited() and visit() are just dummies to represent how the algorithm should look like.

like image 146
Gabi Purcaru Avatar answered Oct 12 '22 23:10

Gabi Purcaru


Python Graph API is a good place to start.

For example, NetworkX has a Kruskal's algorithm implementation to find the minimum spanning tree.

If you want to re-invent the wheel and do it yourself, that is also possible.

like image 20
user225312 Avatar answered Oct 13 '22 00:10

user225312