广度优先搜索 - 算法讲解

🧑‍💻 算法学习 · Breadth-First Search (BFS)

广度优先搜索 (Breadth-First Search (BFS))

概述

难度:中等 (Medium)
分类:Graph Traversal / 图遍历

广度优先搜索是一种层次遍历算法,先访问所有邻居节点,再向外扩展。

BFS is a level-order traversal algorithm that visits all neighbor nodes first before expanding outward.


算法原理

中文:使用队列,从起点开始,先访问所有邻居入队,再依次处理队列中的节点。

English: Using a queue, start from source, enqueue all neighbors, then process nodes in queue order.


复杂度分析

类型 复杂度
时间复杂度 O(V + E)
空间复杂度 O(V)

代码实现

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    
    while queue:
        node = queue.popleft()
        print(node, end=' ')
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return visited

每日练习

  1. 完成算法实现
  2. 分析算法复杂度
  3. 思考:算法的适用场景和局限性

相关阅读:算法专栏


💡 学习建议:算法学习重在理解思想,多写多练是关键。 💡 Learning tip: Algorithm learning is about understanding the core idea. Practice makes perfect.