我需要找到图形的连通分量。我有一个邻居节点列表:
neighbour_list = [[4], [2, 5], [1, 3, 8], [2, 14], [0, 9], [1], [10, 12], [13], [2, 14], [4, 10, 15], [6, 9], [17], [6], [7, 19, 20], [3, 8], [9, 21], [22], [11, 18], [17, 19], [13, 18, 26], [13, 26], [15, 27], [16, 23], [22, 24, 28], [23, 25, 29], [24], [19, 20, 30, 31], [21], [23, 29], [24, 28], [26, 31], [26, 30]]
例如节点 0 有邻居 4,节点 1 有邻居 2 和 5 等等......我想要找到的是一个连接组件的列表。假设节点 0 有邻居 4,但邻居 4 也是节点 9 的邻居。节点 9 也有编号 10 和 15 的邻居。所以列表将类似于
[4,10,15....] etc including following neihbours.
我尝试使用的方法是广度优先搜索。我写了以下算法:
def bfs(neighbour_list, node):
label_list =[]
for sub_neighbour_list in neighbour_list:
label_list.append(node)
queue = [node]
while queue:
u = queue[0]
for sub_neighbour in neighbour_list[u]:
if sub_neighbour not in queue:
label_list[sub_neighbour] = 0
queue.append(sub_neighbour)
queue.pop(0)
print(label_list)
return (label_list)
当我运行它时没有任何反应。怎么了?
谢谢