Breadth-first search

From Simple English Wikipedia, the free encyclopedia
Jump to navigation Jump to search

In computer science, breadth-first search (BFS) is a method used for traversing a graph. It starts at an arbitrary item of a graph and explores all of the neighbor items at the present depth prior to moving on to the items at the next depth level. A breadth-first search done on a tree (data structure) is called a level-order traversal.

Animated example of a breadth-first search (level-order traversal) within a tree.

Implementation[change | change source]

void breadthFirstSearch(Item root) {
    Queue q = new Queue();
    root.found = true;
    q.enqueue(item);
    while (!q.isEmpty()) {
        Item v = q.dequeue();
        for (Item neighbor : v.neighbors()) {
            if (!neighbor.found) {
                neighbor.found = true;
                q.enqueue(neighbor);
            }
        }
    }
}

Related pages[change | change source]