python - 深度优先搜索的输出中缺少节点

标签 python graph

graph = {}

def dfs(graph, node, visited):
    if node not in visited:
        visited.append(node)
        for n in graph[node]:
            dfs(graph,n, visited)
    return visited

n = int(input())
drinks = [d for d in input().split()]
m = int(input())
obs = []
for _ in range(m):
    di, dj = input().split()
    obs += [(di, dj)]

for drink in drinks:
    graph[drink] = []

for drink1, drink2 in obs:
    graph[drink1].append(drink2)
    
order = dfs(graph,drinks[0], [])
print(order)

大家好!

我应该输入一定数量的饮料及其名称。之后,我必须输入组合的数量以及实际上充当图形顶点的组合

示例输入为:

7
A B C D E F G
12
A B
A C
A D
B D
B E
C F
D C
D F
E D
G D
G E
G F

问题是我的输出是['A', 'B', 'D', 'C', 'F', 'E']。它缺少 'G' 并且不是三个可能的输出之一 ['A','B','G','E','D','C',' F']['A'、'G'、'B'、'E'、'D'、'C'、'F'][ 'G'、'A'、'B'、'E'、'D'、'C'、'F']。我不知道为什么

最佳答案

您构建的图是一个有向图,在这种情况下,没有其他节点指向节点G。这意味着 DFS 无法访问 G,除非 DFS 在 G 本身启动。下面是该图的说明:

enter image description here

如果您打算使用无向图,则可以通过更改将边添加到图中的循环来修复此行为:

for drink1, drink2 in obs:
    graph[drink1].append(drink2)
    graph[drink2].append(drink1)

在本例中,您将构建以下无向图(注意没有箭头):enter image description here

最后,您可能应该更改 dfs 函数以使用 set 而不是列表来跟踪访问的节点,因为检查元素是否包含在列表需要 O(n) 时间,而集合则需要 O(1) 时间:

def dfs(graph, node):
    visited = set()
    if node not in visited:
        visited.add(node)
        for n in graph[node]:
            dfs(graph, n)
    return list(visited)

关于python - 深度优先搜索的输出中缺少节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65542178/

相关文章:

python 缩进失败?

python - 随机加权子图

graph - 强制graphviz中节点的从左到右顺序?

python - 使用 Python/Pandas 库从 JSON 响应中解析数据时遇到问题

python - 运行 `airflow scheduler` 启动 33 个调度程序进程

python - 有什么方法可以在不使用 operator.itemgetter 的情况下对嵌套列表进行排序吗?

algorithm - 具有任何源的最短路径的图遍历

graph - 最短路径更快 - SPFA 算法?

java - Java w.r.t Time 中的图形,但在 Ubuntu 任务管理器中具有类似的平滑增量

python - 在python中对名称列表进行排序