如何在python中表示图形/树,以及如何检测循环?

时间:2023-02-02 00:06:59

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 ?

我想在python中实现kruskal算法我如何去表示树/图以及我应该采用什么方法来检测循环?

2 个解决方案

#1


11  

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:

找到循环的一种简单方法是使用BF或DF搜索:

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.

免责声明:这实际上是一个草图;邻居()、visit()和visit()只是表示该算法应该是什么样子的假人。

#2


4  

Python Graph API is a good place to start.

Python图形API是一个很好的起点。

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

例如,NetworkX有一个Kruskal的算法实现来找到最小生成树。

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

如果你想重新发明*并自己动手,那也是可能的。

#1


11  

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:

找到循环的一种简单方法是使用BF或DF搜索:

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.

免责声明:这实际上是一个草图;邻居()、visit()和visit()只是表示该算法应该是什么样子的假人。

#2


4  

Python Graph API is a good place to start.

Python图形API是一个很好的起点。

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

例如,NetworkX有一个Kruskal的算法实现来找到最小生成树。

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

如果你想重新发明*并自己动手,那也是可能的。