如何构建基于字符的Python BFS搜索

时间:2012-06-23 18:18:54

标签: python tree breadth-first-search

我是Python的新手,并尝试构建一个基于字符的 BFS树,用于打印父子关系。这是一个密切相关的解决方案,但是基于数字的树 在这里找到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)

建议将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

对于图表,我使用networkx库。

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