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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With