深度遍历Python中的图形

时间:2016-01-15 08:03:30

标签: python

我正在尝试深入遍历Python中的图形,包含11个节点。

graph = {'A': ['B', 'C'],
        'B': ['A', 'F'],
        'C': ['D', 'E'],
        'D': ['H', 'J', 'C'],
        'E': ['C', 'F'],
        'F': ['B', 'G'],
        'G': ['F', 'H'],
        'H': ['G', 'D', 'I'],
        'I': ['H', 'K'],
        'J': ['D', 'E', 'K'],
        'K': ['I', 'J']}


current_node = []
viewed_nodes = []
   for i in graph.keys():
    print("I'm at the " + str(i) + " node." + " The nodes connected to " +str(i) + " are " + str(graph[i]))
    print("I'm going to mark the " + str(i) + " node as visited.")
    viewed_nodes.append(str(i))

这是我的代码。我正试图弄清楚如何深入遍历它,意味着在返回并沿着不同的路径行进之前在一行中完成所有这些

1 个答案:

答案 0 :(得分:1)

以下内容已访问所有节点。

graph = {'A': ['B', 'C'],
        'B': ['A', 'F'],
        'C': ['D', 'E'],
        'D': ['H', 'J', 'C'],
        'E': ['C', 'F'],
        'F': ['B', 'G'],
        'G': ['F', 'H'],
        'H': ['G', 'D', 'I'],
        'I': ['H', 'K'],
        'J': ['D', 'E', 'K'],
        'K': ['I', 'J']}


current_node = []
viewed_nodes = []


def traverse(into):
    if into in viewed_nodes:
        return

    viewed_nodes.append(into)

    for outto in graph[into]:
        if outto not in viewed_nodes:
            traverse(outto)

for node in graph:
    traverse(node)

print(sorted(viewed_nodes))

输出:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']