MAD 5305 Graph Theory, Spring 2012
CRN: 21139
Classes: PHY 109, MWF 10:45-11:35am
Assignment 4
– solution
Question 1
.
(2 points)
(a) Describe the breadth first search (BFS) algorithm when applied to a
connected graph.
(b) Explain how BFS can be used to find the components of a disconnected graph.
(c) The time-complexity of BFS when applied to a connected graph with
n
vertices and
m
edges
is
O
(
m
+
n
), where
O
(
x
) denotes a function
f
(
x
) satisfying
f
(
x
)
≤
Cx
for some constant
C >
0
and for all large enough
x
. Give an explanation of the term
time-complexity
, and explain why the
time-complexity of BFS is
O
(
m
+
n
).
Solution
.
(a) Here is a description of BFS using a queue
Q
(which is a data-structure):
The Breadth First Search (BFS) algorithm
Input
. A connected graph
G
= (
V, E
), and an initial vertex
u
∈
V
.
Output
. A BFS tree (
V, E
(
T
)) with root
u
so that for every vertex
v
, the unique path from
u
to
v
is a shortest path between
u, v
in
G
.
1. (Initialization)
E
(
T
) :=
∅
,
first
:= 1,
last
:= 1,
Q
[
first
] :=
u
.
Set
visited
[
u
] :=
true
, and
visited
[
v
] :=
false
for all
v
negationslash
=
u
.
2. (Iteration)
while (
first
≤
last
) do
(that is, while queue is not empty)
3.
x
:=
Q
[
first
],
first
:=
first
+ 1;
4.
for all neighbors
y
of
x
do
5.
if (
visited
[
y
] =
false
) then
6.
last
:=
last
+ 1,
Q
[
last
] :=
y
, add
{
x, y
}
to
E
(
T
),
visited
[
y
] :=
true
;
7.
end if;
8.
end do;
9. end do;
(b) Given a disconnected graph, apply BFS to an aribtrarily chosen vertex
u
, and obtain the set of
vertices (from the spanning tree) of the component containing
u
. Repeat BFS for any un-visited
vertex, and obtain (the vertices from) another component. Oviously this process can be repeated
until all components are found.
(c) The time-complexity of an algorithm is the “number of steps” required by the algorithm in the
worst case
among a set of instances (inputs) with given parameter(s). For example, in BFS, the
set of instances is the set of connected graphs with
n
vertices and
m
edges. In order to find the
time-complexity of BFS, we see that for each execution of the while loop in line 2, the operations
in line 3 are executed once. Thus line 3 is executed
n
times (since graph is connected, and there
are
n
vertices), and hence at most
C
′
n
opertations, for some constant
C
′
, are incurred by line 3.
The for loop in line 4 is executed
summationdisplay
x
∈
V
deg(
x
) = 2
m
times, and each time that the for loop is iterated, a constant number of operations are performed.
Thus, the number of steps incurred by the for loop in line 4 is at most
C
′′
m
for some constant
C
′′
.
This shows that the total number of operations required by BFS is at most
C
(
n
+
m
) for some
constant
C
. In time-complexity, we use
O
(
m
+
n
), denoting that the time-complexity of BFS is
1