【问题标题】:How to construct a Character-based Python BFS Search With如何构建基于字符的 Python BFS 搜索
【发布时间】:2012-06-24 02:24:38
【问题描述】:

我是 Python 新手,正在尝试构建一个 基于字符的 BFS 树来打印父子关系。一个密切相关的解决方案,但是是一个 number-based 树,在这个 在这里找到Printing BFS (Binary Tree) in Level Order with _specific formatting_,特别是以下示例,取自参考:

def printBfsLevels(graph,start):
queue=[start]
path=[]
currLevel=1
levelMembers=1
height=[(0,start)]
childCount=0
print queue
while queue:
visNode=queue.pop(0)
if visNode not in path:
  if  levelMembers==0:
    levelMembers=childCount
    childCount=0
    currLevel=currLevel+1
  queue=queue+graph.get(visNode,[])
  if levelMembers > 0:
    levelMembers=levelMembers-1
    for node in graph.get(visNode,[]):
      childCount=childCount+1
      height.append((currLevel,node))
  path=path+[visNode]

prevLevel=None

for v,k in sorted(height):
    if prevLevel!=v:
      if prevLevel!=None:
        print "\n"
    prevLevel=v
    print k,
return height

g={1: [2, 3,6], 2: [4, 5], 3: [6, 7],4:[8,9,13]}
printBfsLevels(g,1)

建议将不胜感激。谢谢!

【问题讨论】:

  • 把g中的数字换成字符?
  • 你能举个例子吗?例如,当我尝试用“A”替换“1”时,我收到错误消息“A 未定义”。

标签: python tree breadth-first-search


【解决方案1】:

对于图表,我使用 networkx 库。

你应该看看http://networkx.lanl.gov/reference/algorithms.traversal.html

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2017-04-21
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多