Docsity

Breadth First Search Algorithm: A Comprehensive Guide with Examples, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Breadth First Search Algorithm: A Comprehensive Guide with Examples and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Breadth First Search

Yufei Tao

ITEE University of Queensland

In this lecture, we will discuss a simple algorithm—called breadth first search—to traverse all the nodes and edges in a graph once. Our discussion will focus on directed graphs, because the extension to undirected graphs is straightforward.

To make the discussion more interesting, we will cast it in a concrete

problem: single source shortest path (SSSP) with unit weights.

Example

a

b

c

d

e

f

g

h

i

There are several paths from a to g :

a → b → c → d → g (length 4) a → b → c → e → d → g (length 5) a → d → g (length 2)

The last one is a shortest path. In this case, the shortest path is unique. Note that h is unreachable from a.

Single Source Shortest Path (SSSP) with Unit Weights

Let G = (V , E ) be a directed graph, and s be a vertex in V. The goal of the SSSP problem is to find, for every other vertex t ∈ V \ {s}, a shortest path from s to t, unless t is unreachable from s.

BFS

At the beginning, color all vertices in the graph white. And create an empty BFS tree T.

Create a queue Q. Insert the source vertex s into Q, and color it gray (which means “in the queue”).

Make s the root of T.

Example

Suppose that the source vertex is a.

a

b

c

d

e

f

g

h

i

a

BFS tree

Q = (a).

Running Example

After de-queueing a:

a

b

c

d

e

f

g

h

i

a

BFS tree

b d

Q = (b, d).

Running Example

After de-queueing b:

a

b

c

d

e

f

g

h

i

a

BFS tree

b d c

Q = (d, c).

Running Example

After de-queueing c:

a

b

c

d

e

f

g

h

i

a

BFS tree

b d c g e

Q = (g , e). Note: d is not en-queued again because it is black.

Running Example

After de-queueing g :

a

b

c

d

e

f

g

h

i

a

BFS tree

b d c g e (^) f i

Q = (e, f , i).

Running Example

Where are the shortest paths?

a

b

c

d

e

f

g

h

i

a

BFS tree

b d c g e (^) f i

The shortest path from a to any vertex, say, x is simply the path from a to node x in the BFS tree!

The proof will be left as an exercise.

Time Analysis

When a vertex v is de-queued, we spend O(1 + d+(v )) time processing it, where d+(v ) is the out-degree of v.

Clearly, every vertex enters the queue at most once.

The total running time of BFS is therefore

O

v ∈V

1 + d+(v )

= O(|V | + |E |).