我在网站(https://brilliant.org/wiki/depth-first-search-dfs/)中查看了深度优先搜索的代码。然而,实现似乎是错误的。这是他们发布的代码
def depth_first_search(graph):
visited, stack = set(), [root]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex] - visited)
return visited
此特定行会抛出错误
stack.extend(graph[vertex] - visited)
这是我的完整程序
graph = {'A': ['B', 'S'], 'B': ['A'], 'C': ['S', 'F', 'D', 'E'],
'D': ['C'], 'E': ['H', 'C'], 'F': ['C', 'G'], 'G': ['S', 'F', 'H'], 'H': ['G', 'E'], 'S': ['A', 'G', 'C']}
def depth_first_search(graph, root):
visited, stack = set(), [root]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex] - visited)
return visited
print(depth_first_search(graph, 'A'))
这是程序遇到的错误
File "/home/souvik/Sublime-text programs/TestCode124.py", line 47, in
depth_first_search
stack.extend(graph[vertex] - visited)
TypeError: unsupported operand type(s) for -: 'list' and 'set'
代码有什么问题?
答案 0 :(得分:0)
您将graph
的值定义为列表,但该函数期望它们是集合:
graph = {
'A': {'B', 'S'},
'B': {'A'},
'C': {'S', 'F', 'D', 'E'},
...
}