python - 如何创建一个执行深度优先搜索的函数,该搜索在找到给定顶点时停止?
问题描述
嗨,我是 python 新手,我正在努力解决我们在活动中所做的事情。我不太明白如何完成此代码,以便它可以执行深度优先搜索,该搜索在找到给定顶点时停止。
graph = {'0': ['1', '2'],
'1': ['0', '3', '4'],
'2': ['0', '4'],
'3': ['1', '4'],
'4': ['1', '2', '3', '5'],
'5': ['4', '6'],
'6': ['5']}
def dfs(visited, graph, vertex):
print (vertex)
visited.append(vertex)
for neighbour in graph[vertex]:
if neighbour not in visited:
dfs(visited, graph, neighbour)
# implement this function
def dfs_stop(visited, graph, vertex, target):
pass
dfs([], graph, '0')
print
dfs_stop([], graph, '0', '4')
解决方案
在调用其邻居的 DFS 之前,您只需要添加一个检查源节点是否等于目标节点。
def dfs_stop(visited, graph, vertex, target):
print (vertex)
visited.append(vertex)
if (vertex == target): # to break/stop the function
return
for neighbour in graph[vertex]:
if neighbour not in visited:
dfs_stop(visited, graph, neighbour)
推荐阅读
- javascript - 如何重定向到另一个页面?
- sql - 需要找到确定工作流程中的当前步骤
- python - 调用子进程时如何通过窗口提示
- laravel-8 - 如何在 laravel 8 命名空间 App 下添加东西
- c - 如何使用联合或可能使用枚举进行别名?
- php - Code Igniter Ajax 调用设置为 Post 但它仅通过 Get 方法发送数据
- jmeter - 生成报告时出错:org.apache.jmeter.report.dashboard.GenerationException:
- sql - 从事务表中获取最新的 ID 和产品收入
- swift - 集合视图为空白
- facebook - Facebook Graph API - 用户没有足够的权限来加载见解