1 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
我不完全確定我是否理解正確:你的例子意味著你只想要連接的子圖?在有向圖中,存在不止一種連接(弱連接和強(qiáng)連接)。因此,您必須決定要尋找哪一個(gè)。
這可能有效:
import networkx as nx
from itertools import combinations
# The graph in your example (as I understand it)
G = nx.DiGraph((i, i+1) for i in range(5))
num_of_nodes = 3 # Number of nodes in the subgraphs (here 3, as in your example)
subgraphs = [] # List for collecting the required subgraphs
for nodes in combinations(G.nodes, num_of_nodes):
G_sub = G.subgraph(nodes) # Create subgraph induced by nodes
# Check for weak connectivity
if nx.is_weakly_connected(G_sub):
subgraphs.append(G_sub)
combinations(G.nodes, num_of_nodes)迭代num_of_nodes來(lái)自 的許多節(jié)點(diǎn)的所有唯一組合G。
所選的子圖正是您提到的:
print([H.nodes for H in subgraphs])
print([H.edges for H in subgraphs])
節(jié)目
[NodeView((0, 1, 2)), NodeView((1, 2, 3)), NodeView((2, 3, 4)), NodeView((3, 4, 5))]
[OutEdgeView([(0, 1), (1, 2)]), OutEdgeView([(1, 2), (2, 3)]), OutEdgeView([(2, 3), (3, 4)]), OutEdgeView([(3, 4), (4, 5)])]
如果你的圖表是
G = nx.DiGraph([(i, i+1) for i in range(5)] + [(i+1, i) for i in range(5)])
如果您正在尋找強(qiáng)大的連接性,那么您必須使用
...
# Check for strong connectivity
if nx.is_strongly_connected(G_sub):
...
(通常的警告:G.subgraph()只給你一個(gè)視圖。)
添加回答
舉報(bào)