Python:查找连接到n(元组)的所有节点
我想知道是否可以从某个节点到达所有节点。我对路径不感兴趣,如果我能或不能,我只想输出YES或NO。假设我有下面的图-作为约束,我需要将我的节点表示为元组I,j:Python:查找连接到n(元组)的所有节点,python,algorithm,search,graph,path,Python,Algorithm,Search,Graph,Path,我想知道是否可以从某个节点到达所有节点。我对路径不感兴趣,如果我能或不能,我只想输出YES或NO。假设我有下面的图-作为约束,我需要将我的节点表示为元组I,j: graph={ (1,1): [(1,2),(2,2)] (1,2): [(1,3)] (1,3): [(1,2),(2,3)] (2,2): [(3,3)] (2,3): [] (3,3): [(2,2)] } 现在,我需要显示我是否可以从1,1,2,2或3,3,即I,j,I=j,所有
graph={
(1,1): [(1,2),(2,2)]
(1,2): [(1,3)]
(1,3): [(1,2),(2,3)]
(2,2): [(3,3)]
(2,3): []
(3,3): [(2,2)]
}
现在,我需要显示我是否可以从1,1,2,2或3,3,即I,j,I=j,所有其他节点I!=J如果是,打印是-如果否,打印否。
上面提到的示例将为节点1,1输出YES,因为我可以通过节点1,1到达1,2,1,3和2,3
我试着用下面的方法
G = nx.DiGraph()
G.add_edges_from(graph)
for reachable_node in nx.dfs_postorder_nodes(G, source=None):
print reachable_node
但是,如果我在nx.dfs\u postorder.nodes中将1,1,2,2或3,3声明为我的源,我会得到,例如,以下错误->键错误:1,1
哪个函数或库越标准,库越好!!我是否应该使用来指示我是否可以从任何I,I节点到达所有节点
感谢所有的澄清!我是新会员,因此如果我的问题不符合Stackoverflow指南,请随时告诉我如何改进我的下一个问题 我想我理解你的问题。您可以使用如下所示的nx.shortest_路径,尝试使用try/except块的穷举方法:
import networkx as nx
graph={
(1,1): [(1,2),(2,2)],
(1,2): [(1,3)],
(1,3): [(1,2),(2,3)],
(2,2): [(3,3)],
(3,3): [(2,2)],
(4,4): [(1,3)],
(5,5): []
}
G = nx.Graph(graph)
nodes = G.nodes()
balanced_nodes = [node for node in G.nodes() if node[0] == node[1]]
unbalanced_nodes = [node for node in G.nodes() if node[0] != node[1]]
for balanced_node in balanced_nodes:
for unbalanced_node in unbalanced_nodes:
connected = True
try:
path = nx.shortest_path(G,balanced_node, unbalanced_node)
except:
connected = False
break
print(balanced_node, ": ", connected)
这导致:
(1, 1) : True
(2, 2) : True
(3, 3) : True
(4, 4) : True
(5, 5) : False
这个程序应该完成这项工作,它只使用标准库,基本上为您提供了在给定起点可以访问的所有可能状态:
graph={
(1,1): [(1,2), (2,2)],
(1,2): [(1,3)],
(1,3): [(1,2), (2,3)],
(2,2): [(3,3)],
(2,3): [],
(3,3): [(2,2)]
}
node0 = (1,1) #choose the starting node
node0_connections = [node0] #this list will contain all the possible states that can be visited from node0
for node in node0_connections:
for node_to in graph[node]:
if node0_connections.count(node_to) == 0:
node0_connections.append(node_to)
print 'All possible states to be visted from node', node0,':', node0_connections,'.'
count = node0_connections.count((1,2)) + node0_connections.count((1,3)) + node0_connections.count((2,2))
if count == 3:
print 'YES'
else:
print 'NO'
我只是想知道节点i,j的元组中的值i,j是什么意思?@svasa-i,j都是可以在元组中表示i和j的可能变体。例如,如果我们有4个节点n=4,我们的图将表示i=1,…,4和j=1,…,4的所有组合。2,3=3,2在这种情况下,我尝试在没有nx.dfs\u postorder.nodes的情况下使用最短路径。这就是你想要的吗?谢谢@briancaffey!:谢谢@Ton!: