Python:查找连接到n(元组)的所有节点

时间:2018-02-10 16:04:30

标签: 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,所有其他节点i!=学家如果是,则打印(是) - 如果否,则打印(否)。 上面提到的例子将为节点(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_postorder.nodes()中声明(1,1),(2,2)或(3,3)作为我的源,我得到,例如,跟随错误 - > KeyError:(1,1)

我应该使用哪个函数或库(库越标准越好!!)来指示我是否可以从任何(i,i)节点到达所有节点?

感谢所有澄清!我是新会员,如果我的问题没有遵循Stackoverflow指南,请随时告诉我如何改进我的下一个问题!

2 个答案:

答案 0 :(得分:3)

该程序应该完成工作并且它只使用标准库(基本上为您提供了可以访问给定起点的所有可能状态):

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'

答案 1 :(得分:1)

我想我理解你的问题。您可以尝试使用try/except阻止使用nx.shortest_path这样的详尽方法:

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