Bidirectional Search

About

Bidirectional search is an advanced graph search algorithm that runs two simultaneous searches:

  • Forward Search: Starts from the initial node.

  • Backward Search: Starts from the goal node.

  • The search stops when both searches meet in the middle.

Implementation Strategy

To implement bidirectional search:

  1. Use two queues for BFS traversal from the start and goal nodes.

  2. Maintain two visited sets to track explored nodes.

  3. Stop when the search frontiers meet.

Graph Representation (Adjacency List)

import java.util.*;

class Graph {
    private final Map<Integer, List<Integer>> adjList;

    public Graph() {
        this.adjList = new HashMap<>();
    }

    // Add edge in an undirected graph
    public void addEdge(int source, int destination) {
        adjList.putIfAbsent(source, new ArrayList<>());
        adjList.putIfAbsent(destination, new ArrayList<>());
        adjList.get(source).add(destination);
        adjList.get(destination).add(source);
    }

    // Returns the adjacency list
    public List<Integer> getNeighbors(int node) {
        return adjList.getOrDefault(node, new ArrayList<>());
    }

    // Print the graph
    public void printGraph() {
        for (var entry : adjList.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

Bidirectional Search Algorithm

Testing the Algorithm

Time Complexity Analysis

Search Algorithm

Time Complexity

BFS (Single Direction)

O(b^d)

Bidirectional Search

O(b^{d/2})

Where:

  • b = branching factor (average number of neighbors per node)

  • d = depth of the shortest path

Why is Bidirectional Search Faster?

  • BFS explores b^d nodes, but bidirectional search only explore 2xb^{d/2} nodes.

  • This leads to an exponential reduction in search space.

For example, if b=10 and d=6:

  • BFS explores 10^6 = 1,000,000 nodes.

  • Bidirectional search explores 2 x 10^3 = 2,000 nodes, which is significantly smaller.

Last updated