The below pseudocode finds the
shortest path from a given vertex to all other vertices in the graph using BFS.
Input: A graph and a starting vertex of
Output: Goal state. The
parent links trace the shortest path back to 1
procedure BFS(
G,
root)
is 2 let
Q be a queue 3 label
root as explored 4
Q.enqueue(
root) 5
while Q is not empty
do 6
v :=
Q.dequeue() 7
if v is the goal
then 8
return v 9
for all edges from
v to
w in G.adjacentEdges(
v)
do 10
if w is not labeled as explored
then 11 label
w as explored 12
w.parent :=
v 13
Q.enqueue(
w)
More details with some connections between cities This non-recursive implementation is similar to the non-recursive implementation of
depth-first search, but differs from it in two ways: • it uses a
queue (
First In First Out) instead of a
stack (Last In First Out) and • it checks whether a vertex has been explored before enqueueing the vertex rather than delaying this check until the vertex is dequeued from the queue. If is a
tree, replacing the queue of this breadth-first search algorithm with a stack will yield a depth-first search algorithm. For general graphs, replacing the stack of the iterative depth-first search implementation with a queue would also produce a breadth-first search algorithm, although a somewhat nonstandard one. The
Q queue contains the frontier along which the algorithm is currently searching. Nodes can be labelled as explored by storing them in a set, or by an attribute on each node, depending on the implementation. Note that the word
node is usually interchangeable with the word
vertex. The
parent attribute of each node is useful for accessing the nodes in a shortest path, for example by backtracking from the destination node up to the starting node, once the BFS has been run, and the predecessors nodes have been set. Breadth-first search produces a
breadth-first tree which is shown in the example below.
Example The lower diagram shows the breadth-first tree obtained by running a BFS on an example graph of
German cities (upper diagram) starting from
Frankfurt. == Analysis ==