Jump to content

Bidirectional search

From Simple English Wikipedia, the free encyclopedia

In computer science, bidirectional search is a method used for finding the shortest path between two items in a graph. It runs two simultaneous searches starting from the two items.[1]

Implementation

[change | change source]

The example below uses two simultaneous breadth-first searches.

void bidirectionalSearch(Item a, Item b) {
    Queue qA = new Queue();
    Queue qB = new Queue();
    qA.enqueue(a);
    qB.enqueue(b);
    while (!qA.isEmpty() && !qB.isEmpty()) {
        if (!qA.isEmpty()) {
            Item v = qA.dequeue();
            if (aItem.found) return true;
            for (Item neighbor : v.neighbors()) {
                if (!neighbor.found) {
                    neighbor.found = true;
                    qA.enqueue(neighbor);
                }
            }
        }
        if (!qB.isEmpty()) {
            Item v = qB.dequeue();
            if (v.found) return true;
            for (Item neighbor : v.neighbors()) {
                if (!neighbor.found) {
                    neighbor.found = true;
                    qB.enqueue(neighbor);
                }
            }
        }
    }
    return false;
}
[change | change source]

References

[change | change source]
  1. "Bidirectional search". Planning Algorithms. UIUC. Archived from the original on 21 February 2020. Retrieved 11 October 2020.