尝试在有向图中显示所有节点时,会显示错误的节点!
这是什么,我在这里做错了?另外,我如何使用图形字典而不是定义所有边缘,有没有办法使用字典?
预期结果:
1 --> Node(s): ['2', '4']
2 --> Node(s): ['3', '5', '7']
3 --> Node(s): ['1', '6']
4 --> Node(s): ['6']
5 --> Node(s): ['7', '8']
6 --> Node(s): ['8']
7 --> Node(s): ['8', '9']
8 --> Node(s): ['9']
实际结果:
1 --> Node(s): [2, 3, 4]
2 --> Node(s): [1, 3, 5, 7]
3 --> Node(s): [1, 2, 6]
4 --> Node(s): [1, 6]
5 --> Node(s): [2, 7, 8]
6 --> Node(s): [3, 4, 8]
7 --> Node(s): [2, 5, 8, 9]
8 --> Node(s): [5, 6, 7, 9]
9 --> Node(s): [7, 8]
如果使用图表字典:
graph = {'1': ['2','4'], '2': ['3', '5', '7'], '3': ['1','6'], '4': ['6'],
'5': ['7','8'], '6': ['8'], '7': ['8', '9'], '8': ['9']}
代码:
n_nodes = {}
# Search for all nodes and create an empty array for each node
def add_nodes(node_array):
for node in node_array:
if node not in n_nodes:
n_nodes[node] = []
def add_edge(edge):
u, v = edge
if (v not in n_nodes[u]) and (u not in n_nodes[v]):
n_nodes[u].append(v)
if (u != v):
n_nodes[v].append(u)
add_nodes([i+1 for i in range(9)])
add_edge((1,2))
add_edge((1,4))
add_edge((2,3))
add_edge((2,5))
add_edge((2,7))
add_edge((3,1))
add_edge((3,6))
add_edge((4,6))
add_edge((5,7))
add_edge((5,8))
add_edge((6,8))
add_edge((7,8))
add_edge((7,9))
add_edge((8,9))
# Print All Nodes
for key in sorted(n_nodes):
print (key, " --> Node(s):",sorted(n_nodes[key]))
答案 0 :(得分:0)
您的代码将边视为无向边:它们始终在两个方向上添加。所以只需删除在相反方向添加边缘的代码。
改变这个:
if (v not in n_nodes[u]) and (u not in n_nodes[v]):
n_nodes[u].append(v)
if (u != v):
n_nodes[v].append(u)
...为:
if v not in n_nodes[u]:
n_nodes[u].append(v)