【发布时间】:2019-06-04 12:38:49
【问题描述】:
我正在尝试在 Python 3.7 中实现 kruskal 算法。
所以我编写了一个程序“bfs”来进行广度优先搜索,我想用它来检查在 kruskal 算法中添加到最小生成树的边是否不会创建一个圆。
from collections import deque #we import a queue structure
def bfs(G, startnode, endnode=None):
B = {startnode}
Q = deque([startnode])
L = []
while Q:
v = Q.pop()
L.append(v)
#If a final node was specified we will end the search there (including the final node)
if v == endnode:
break
for neighbor in G.neighbors(v):
if not neighbor in B:
B.add(neighbor)
Q.appendleft(neighbor)
return L
上面的代码应该是正确的,并且为了完整性而发布。接下来我们有 kruskal 的算法实现:
import networkx as nx
def kruskal_bfs(G):
V =nx.Graph()
edges=sorted(G.edges(data=True), key=lambda t: t[2].get('weight', 1)) #sorts the edges (from stackoverflow)
E_F = set([]) #mimimum spanning tree
for edge in edges:
E_F.add((edge[0],edge[1])) #add edge to the mimumum spanning tree
V.add_edges_from(list(E_F)) #combine it with the nodes for bfs
startnode = edge[0]
if bfs(V,startnode) == bfs(V, ):
E_F.remove(edge)
V.remove_edges_from(list(V.edges())) #reset edges of V
return E_F
我有if bfs(V,startnode) == bfs(V, ): 的部分是我有点卡住的地方,如果条件我怎么能完成这个。我尝试扩展bfs 以包含某种形式的“圆检测”。然而这并没有奏效。
【问题讨论】:
标签: graph-theory graph-algorithm discrete-mathematics kruskals-algorithm