Bidirectional BFS is applicable to the case where the target node is known; the initial node expands toward the target node and the target node expands toward the initial node at the same time, until the same node appears in both expansion directions, and the search ends. For example, in a maze, when we need to know the number of steps to reach each location, a normal BFS is sufficient, but if we only need to know the number of steps to reach a specific location, we should use a two-way BFS. Start BFS from two target points at the same time, so we will have two different queues. Update the smaller one each time until there are elements in the two queues that overlap, indicating that the path is found. For example in the following graph, it will stop at node 9.
Time Complexity
Suppose if the branching factor of the tree is b and the distance between the target vertex and the source is d, then the normal BFS search complexity will be $O(b^d)$. On the other hand, if we perform two search operations, the complexity of each search will be $O(b^{d/2})$ and the total complexity will be $O(b^{d/2} + b^{d/2})$, which is much less than $O(b^d)$.
The branch factor refers to the number of children of each node in the expanded tree, i.e., the number of new elements that can be reached by each element. For example, in a maze where you can only move up and down, the branch factor is 4.
Word Ladder
Word Ladder is a hard level question. It can be solved by using BFS. However BFS will time out. We can use Bidirectional to solve this issue.
1 | class Solution { |
This problem is also the first assignment of COMP6771 in 20T2.