【问题标题】:DFS without skipping visited nodes pythonDFS不跳过访问节点python
【发布时间】:2021-03-24 03:42:36
【问题描述】:

我正在编写以下代码来实现 dfs 而不会跳过访问的节点。对于以下示例图,使用 a 作为根。第一个分支可以是 a-b-c-d。然后遍历b的另一个分支,b-d。然后遍历a的另一个分支,a-d,然后是a-e。这棵树的形状应该是 为了结束循环,我将使用深度。例如如果深度等于 3,那么一个树分支最多有 3 个节点。有一个示例图:

G = {'a': set(['d','b','e']),
     'b': set(['a', 'c', 'd']),
     'c': set(['b','d']),
     'd': set(['a','b','c']),
     'e': set(['a'])}

深度等于3,a作为开始,我的预期结果是a b c d d d c e。
我已经尝试了一段时间,但没有运气。这是我当前的代码:

def depth_first_search(graph, start,maxdepth):
    depth={start:0}
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        print(vertex)
        if depth[vertex]==maxdepth:
           break
        # if vertex not in visited:
        #     visited.add(vertex)
        #    for neighbor in set(graph[vertex]-visited):
        for neighbor in graph[vertex]:
                # if neighbor in depth:
                #      continue
                stack.extend(neighbor)
                depth[neighbor]=depth[vertex]+1
    return depth

【问题讨论】:

  • 我不明白。您想要一个不检查访问节点的 DFS?在这种情况下,您将陷入循环。请详细解释一下。
  • 感谢您的评论。我会编辑更多。

标签: python depth-first-search


【解决方案1】:

由于到目前为止没有人回答我的问题。我想发布我最近发现的。欢迎不同的想法。

def buildtree_draft(G,k):
    remove=[]
    if len(G) <= 2:
        return
    else:
        for node in list(G.nodes()):
            remove.append(node)
            for node1 in list(G.neighbors(node)):
                set1=set([node,node1])
                li.append(set1)
                for item in li:
                    if item not in result:
                        result.append(item)
                for node2 in list(G.neighbors(node1)):
                    if node2==node:
                        continue
                    else:
                        set2=set([node,node1,node2])
                        li.append(set2)
                        for item in li:
                            if item not in result:
                                result.append(item)
            G.remove_nodes_from(remove) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    相关资源
    最近更新 更多