algorithm - 如何跟踪广度优先搜索的深度?

标签 algorithm data-structures graph graph-algorithm

我有一个树作为广度优先搜索的输入,我想知道随着算法的进展它在哪个级别?

# Breadth First Search Implementation
graph = { 
    'A':['B','C','D'],
    'B':['A'],
    'C':['A','E','F'],
    'D':['A','G','H'],
    'E':['C'],
    'F':['C'],
    'G':['D'],
    'H':['D']
    }


def breadth_first_search(graph,source):
    """
    This function is the Implementation of the breadth_first_search program
    """
    # Mark each node as not visited
    mark = {}
    for item in graph.keys():
        mark[item] = 0

    queue, output = [],[]

    # Initialize an empty queue with the source node and mark it as explored
    queue.append(source)
    mark[source] = 1
    output.append(source)

    # while queue is not empty
    while queue:
        # remove the first element of the queue and call it vertex
        vertex = queue[0]
        queue.pop(0)
        # for each edge from the vertex do the following
        for vrtx in graph[vertex]:
            # If the vertex is unexplored
            if mark[vrtx] == 0:
                queue.append(vrtx)  # mark it as explored
                mark[vrtx] = 1      # and append it to the queue
                output.append(vrtx) # fill the output vector
    return output

print breadth_first_search(graph, 'A')

它以树作为输入图,我想要的是,在每次迭代时它应该打印出正在处理的当前级别。

最佳答案

实际上,我们不需要额外的队列来存储当前深度的信息,也不需要添加 null 来判断当前级别是否结束。我们只需要知道当前层包含多少个节点,然后我们就可以处理同一层的所有节点,处理完当前层的所有节点后,层级增加1。

int level = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
    int level_size = queue.size();
    while (level_size-- != 0) {
        Node temp = queue.poll();
        if (temp.right != null) queue.add(temp.right);
        if (temp.left != null) queue.add(temp.left);
    }    
    level++;
}

关于algorithm - 如何跟踪广度优先搜索的深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247634/

相关文章:

algorithm - 在图上使用 DFS - 确定图是否是具有特定 SCC 的团

java - 修剪有向图的叶子组件

java - 查找达到给定值的最小包装数

c++ - 用有限的钱购买元素的算法

algorithm - 为什么在链表中查找循环时将指针增加 2,为什么不增加 3、4、5?

c - 当我们声明 struct node *p = NULL; 时,我们的意思是什么?

python - 如何在 igraph 中提取某些路径类型?

arrays - 具有 O(1) 插入和删除的双向链表的紧凑多数组实现

algorithm - 生成总和为给定数字的统一二进制数组

string - 使用长公共(public)前缀进行更快的字符串排序?