我想标记连接组件的所有元素。图表的链接使用字典字典格式化。具有递归的算法似乎很快,不幸的是对于较大的图形,最大递归深度产生问题并且我不希望每次都增加最大递归长度。你知道如何重写这段代码,深度不再麻烦了吗?
import numpy as np
def find_components(dists):
N = len(dists.keys())
labels = np.zeros(N, dtype = np.int) - 1
n = 0
steps = 0
def walk(j):
for k in dists[j].keys():
if (labels[k] == -1):
labels[k] = labels[j]
walk(k)
remains = (labels == -1)
while n < N:
i = np.arange(0,N,1)[remains][np.random.randint(0,N - n)]
labels[i] = i
walk(i)
remains = (labels == -1)
n = N - len(np.nonzero(remains)[0])
unique = np.unique(labels)
labels_ = np.zeros(N, dtype = np.int) - 1
for i, label in enumerate(unique):
labels_[labels == label] = i
return labels_
答案 0 :(得分:1)
将walk()
从递归函数转换为迭代版本:
import collections
def walk(j):
lifo = collections.deque(j)
while lifo:
for k in dists[lifo.pop()].keys():
if labels[k] == -1:
labels[k] = labels[j]
lifo.append(k)