简体   繁体   English

在Python中深度遍历图形

[英]Depth Traversing a graph in Python

I'm trying to depth traverse a graph in Python, with 11 nodes. 我正在尝试用11个节点在Python中深度遍历图。

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))

This is my code. 这是我的代码。 I'm trying to figure out how to depth traverse it, meaning go through it all in one line before going back and going down different paths 我正在尝试找出如何进行深度遍历,这意味着在回溯并沿着不同的路径前进之前,先将其全部遍历

This below already visits all nodes. 下面的内容已访问所有节点。

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))

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM