Authored by Tony Feng
Created on April 6th, 2022
Last Modified on April 6th, 2022
Understanding BFS
Intro
- Breadth-First Search (BFS) is an algorithm used for traversing graphs or trees.
- Breadth-First Search is a recursive algorithm to search all the vertices of a graph or a tree.
- BFS starts from a node, then it checks all the nodes at distance I from the beginning node, then it checks all the nodes at distance II, and so on. In order to re-collect the nodes to be visited, BFS uses a queue.
- The time complexity of DFS if the entire tree is traversed is O(V), where V is the number of nodes.
- In the case of a graph, the time complexity is O(V + E), where V is the number of vertexes and E is the number of edges.
- Please note that O(E) may vary between O(1) and O(V2), depending on how dense the graph is.
Steps of BFS
- Add the root/start node to the
Queue
. - For every node, set that they don’t have a defined parent node.
- Until the
Queue
is empty:- Extract the node from the beginning of the
Queue
. - Perform output processing.
- For every neighbor of the current node that doesn’t have a defined parent (is not visited), add it to the
Queue
, and set the current node as their parent.
- Extract the node from the beginning of the
Template
|
|
Examples
Leetcode 102 Binary Tree Level Order Traversal
|
|
Leetcode 200 Number of Islands
|
|
Reference
- 手把手带你刷Leetcode力扣 - 广度优先搜索 BFS
- 手把手带你刷Leetcode力扣 - Leetcode 102
- 手把手带你刷Leetcode力扣 - Leetcode 107
- 手把手带你刷Leetcode力扣 - Leetcode 200
- Breadth First Search in Python (with Code) | BFS Algorithm
- Graphs in Python: Breadth-First Search (BFS) Algorithm
- What is Breadth First Search?