bfs中的跟踪深度

时间:2018-09-26 08:30:26

标签: python

我正在尝试找到根与要遍历的节点深度之间的距离

2 个答案:

答案 0 :(得分:0)

您可以将节点及其级别排成元组,而不是仅对节点进行排队,并且在将一个节点排入队列时,它总是与当前级别加一,因此当您将一个节点排出队列并将该节点附加到{ {1}}还可以从元组中获取节点的级别:

visit_order

这样:

import collections
def bfs(graph, root):
    seen, queue = {root}, collections.deque([(root, 0)])
    visit_order = []
    levels = []
    while queue:
        vertex, level = queue.popleft()
        visit_order.append(vertex)
        levels.append(level)
        for node in graph.get(vertex, []):
            if node not in seen:
                seen.add(node)
                queue.append((node, level + 1))

    print(visit_order)
    print(levels)

将输出:

bfs({ 1: [2, 3], 2: [4], 3: [5]}, 1)

答案 1 :(得分:0)

您可以使用字典来跟踪当前深度:

router.get('/google/redirect',passport.authenticate('google',{ session: false }),AuthController.googleLogin);

输出:

from collections import deque
d = {1: [2, 3], 2: [4], 3: [5]}
def bfs(graph, root = 1):
   queue, seen, depths = deque([root]), [], {root:0}
   while queue:
     val = queue.popleft()
     depths.update({i:depths[val] +1 for i in graph.get(val, [])})
     seen.append(val)
     queue.extend([i for i in graph.get(val, []) if i not in seen])
   yield seen, depths

[(_all, _depths)] = bfs(d)
print([_depths[i] for i in _all])

逻辑更简单,但是,在使用[0, 1, 1, 2, 2] 时,可以应用深度优先遍历:

class

输出:

class Tree:
  def __init__(self, _start):
     self.__dict__ = {'head':_start, 'data':[Tree(i) for i in d.get(_start, [])]}
  def __contains__(self, _val):
     if self.head != _val and not self.data:
       return False
     return True if self.head == _val else any(_val in i for i in self.data)
  def get_depth(self, _val):
     if self.head == _val:
       return 0
     return 1+[i for i in self.data if _val in i][0].get_depth(_val)

t = Tree(1)
print([t.get_depth(i) for i in set([i for a, b in d.items() for i in [a, *b]])])