Chapter 38: Breadth-First Search

前言

BFS是用來走遍圖上的每一個點,走的方式是走第一層鄰居,走完接著走下一層鄰居。通常用在圖上有很多相連的點。

大綱

  • Example

  • Implementation

  • Performance

Example

  • Use a queue to keep track of which vertices to visit next

  • It’s important to note that you only add a vertex to the queue when it has not yet been visited and is not already in the queue.”

Implementation

Performance

  • The overall time complexity for breadth-first search is O(V + E).

    • Each vertex is enqueued once. This has a time complexity of O(V).

    • During this traversal, you also visit all the the edges. The time it takes to visit all edges is O(E).

  • The space complexity of BFS is O(V),

    • since you have to store the vertices in three separate structures: queue, enqueued and visited.

Last updated