Python图递归

标签 python recursion

d={'a':['b','d'],'b':['c'],'c':['d']}

def path(d,consider,end,route=''):
    if consider==end:

        return route
    else:
        for e in d[consider]:
            print(e)
            route = path(d,e,end,route)
            route=str(e)+route
            print route

            return route

path(d,'a','d') 打印:

b
c
d
d
cd
bcd
Out[89]:
'bcd'

为什么它不打印'a'的第二个考虑因素,即'd'。它输出“b”的分支,但似乎没有探索“d”,即使它应该由 for 循环进行。

最佳答案

您还可以使用广度优先搜索来查找最短路径:

import collections
def path(d, consider, end):
  queue = collections.deque([consider])
  seen = []
  flag = False
  while queue:
    val = queue.popleft()
    if val == end:
      return seen
    seen.append(val)
    queue.extend([i for i in d[val] if i not in seen])
  return flag

result = path({'a':['b','d'],'b':['c'],'c':['d']}, 'a', 'd')
result = result if result else []
print(result)

输出:

['a', 'b']

关于Python图递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746076/

相关文章:

Python os.stat 不扩展文件名中的通配符

Python 数独解算器速度慢

javascript - 递归函数无法正常工作

python - 如何为图中的每条绘制线选择新颜色

python - 我无法从 Express 应用程序执行 python 脚本

python - Pyshark不捕获任何数据包

python - 如何收集结构任务输出并打印多个主机的摘要?

C++:使用递归和引用变量查找数组中的最大元素

java - 作业问题: Need just a hint for the base case to throw an exception for a recursive binary search when a word doesn't exist

c++ - 递归函数破坏一般树c++