#广度优先搜索

graph = {
    'S' : ['A','B'],
    'A' : ['B','C','D'],
    'B' : ['C'],
    'C' : ['D'],
    'D' : []
}
visited = []
queue = []
goal = 'D'
def bfs(visited, graph, node):
  visited.append(node)
  queue.append(node)
  while queue : 
    s = queue.pop(0)
    print(s, end = "\n")
    for neighbour in graph[s]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)
        if goal in visited:
          break
bfs(visited,graph,'S')          

#上述代码用于遍历路径.有谁能告诉我找到最短路径的密码.上述代码的输出为S A B C D

推荐答案

由于所有边都具有相同的权重或没有权重,因此可以通过以下方式应用BFS来查找最短路径-第一次遇到 node 时,这意味着到该 node 的路径是最短的,因此对于每个访问过的顶点,可以保留通向它的上一个顶点,然后在遇到目标顶点时恢复该路径:

visited_paths = {}
queue = []
goal = 'D'
def bfs(visited, graph, node):
  visited[node] = node # path to start includes start
  queue.append(node)
  while queue: 
    s = queue.pop(0)
    if(s == goal):
        break

    for n in graph[s]:
        if n not in visited:
            queue.append(n)
            visited[n] = s # set previous node when node is first encountered

  if goal in visited:
    # restore the path
    path = [goal]
    curr = goal
    while curr != node:
       curr = visited[curr]
       path.append(curr)
    path.reverse() # reverse path to get correct order
    print(path)
  else:
    print("No path")

bfs(visited_paths,graph,'S')    

Python相关问答推荐

多处理代码在while循环中不工作

配置Sweetviz以分析对象类型列,而无需转换

使用plotnine和Python构建地块

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

如何将双框框列中的成对变成两个新列

删除字符串中第一次出现单词后的所有内容

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

从spaCy的句子中提取日期

Python+线程\TrocessPoolExecutor

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

Pandas Loc Select 到NaN和值列表

幂集,其中每个元素可以是正或负""""

干燥化与列姆化的比较

从旋转的DF查询非NaN值

使用__json__的 pyramid 在客户端返回意外格式

判断Python操作:如何从字面上得到所有decorator ?

如何在一组行中找到循环?

TypeError:';Locator';对象无法在PlayWriter中使用.first()调用

ValueError:必须在Pandas 中生成聚合值

如何计算Pandas 中具有特定条件的行之间的天差