试图在 Python 中找到断开连接的图

Trying to find disconnected Graphs in Python

我希望在 Python

中找到断开连接的子图

以此图为例: 索引 0 代表节点 A , 1 代表 B ... 等 -1 只是一个占位符,因为这是一个没有边连接自身的简单图形。

5代表边的权重(以后会有不同权重的图)

[[-1  5  5  0  0]
 [ 5 -1  0  0  0]
 [ 5  0 -1  0  5]
 [ 0  0  0 -1  0]
 [ 0  0  5  0 -1]]

为了寻找断开连接的图形,我首先创建了一个 True / False 判断我是否访问过边缘。 ( 0 和 -1 是默认值,True)看起来像这样:

[[ True False False  True  True]
 [False  True  True  True  True]
 [False  True  True  True False]
 [ True  True  True  True  True]
 [ True  True False  True  True]]

我解决这个问题的方法是从任何一条有假值的边开始,从行代表的节点开始,遍历连接该节点和它的子节点的所有可能的边,等等。当我遍历这些顶点时,我会将布尔矩阵标记为真,因为我有 "visited" 那个边。一旦我知道我有 "visited" 所有边,我就知道我将有一个连接的子图。 然后我将在我的 True/False 矩阵中寻找另一个 "False" 并从那里开始寻找另一个断开连接的图形,并继续直到我将所有元素都填充为 True。

但是,我一直停留在遍历边缘

这是我的算法:

reducedMatrix = np.load(reducedweightmatrix)
print(reducedMatrix)
boolarray = (reducedMatrix == 0) | (reducedMatrix == -1)
print(boolarray)


def traverse(iy,visited_nodes,looped):
    #Only move to next index if there is no loop
    # already visited node?
    print("I am currently at: "+ str(iy))
    print(visited_nodes)
    print(looped)
    print("-----------------\n")
    if (iy in visited_nodes):
        looped = True
    if(not looped):
        print("I enterred the loop")
        children = []
        #Find connected "children" vertices
        for ix,weight in enumerate(reducedMatrix[iy]):
            if weight != 0 and weight != -1:
                #Collect the index with connected vertices
                children.append(ix)
                #I AM GOING TO VISIT  THESE VERTICES
                boolarray[iy,ix] = True

        print(children)
        visited_nodes.append(iy) 
        for child,children in enumerate(children):
            print(child)
            traverse(child,visited_nodes,looped)
    return visited_nodes

print(traverse(0,[],False))

使用上面显示的示例,这里是日志消息:

[[-1  5  5  0  0]
 [ 5 -1  0  0  0]
 [ 5  0 -1  0  5]
 [ 0  0  0 -1  0]
 [ 0  0  5  0 -1]]
[[ True False False  True  True]
 [False  True  True  True  True]
 [False  True  True  True False]
 [ True  True  True  True  True]
 [ True  True False  True  True]]
I am currently at: 0
[]
False
-----------------

False
I enterred the loop
[1, 2]
0
I am currently at: 0
[0]
False
-----------------

True
1
I am currently at: 1
[0]
False
-----------------

False
I enterred the loop
[0]
0
I am currently at: 0
[0, 1]
False
-----------------

True
[0, 1]

根据上面的例子,算法应该显示如下: [0,1,2,4] 请指出递归哪里出错了

这段代码我不是很懂,

for child,children in enumerate(children):
    print(child)
    traverse(child,visited_nodes,looped)

只需将其更改为,

for child in children:
    print(child)
    traverse(child,visited_nodes,looped)

答案就在那边。

你要的是访问children中的每一个child,而不是children的索引。你之前在children中保存的是索引号。您确定不想查找索引号的索引。

编辑:如果您正在迭代一个可迭代对象,请不要将您的值命名为与可迭代对象本身相同的名称。猜猜下面会发生什么?

children = list(range(10))  
for child,children in enumerate(children):
    pass
print(children)