Breadth First Search. Representations of Graphs. Two standard ways to represent a graph Adjacency lists, Adjacency Matrix Applicable to directed and undirected graphs. Adjacency lists Graph G(V, E) is represented by array Adj of | V | lists
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.
Breadth FirstSearch
Representations of Graphs
Adjacency lists
1 if (i, j) E
0 otherwise
aij={
1
2
3
5
4
1
2
2
5
4
4
Adjacency Matrix
A = AT
Breadth First Search
Breadth First Search
BFS(G, s)
1 for each vertex u V [G] – {s}
2 do color [u] ← WHITE
3 d [u] ← ∞
4 π[u] ← NIL
5 color[s] ← GRAY
6 d [s] ← 0
7 π[s] ← NIL
8 Q ← Ø /* Q always contains the set of GRAY vertices */
9 ENQUEUE (Q, s)
10 while Q ≠ Ø
11 do u ← DEQUEUE (Q)
12 for each v Adj [u]
13 do if color [v] = WHITE /* For undiscovered vertex. */
14 then color [v] ← GRAY
15 d [v] ← d [u] + 1
16 π[v] ← u
17 ENQUEUE(Q, v)
18 color [u] ← BLACK
Q
Except root node, s
For each vertex u V(G)
color [u] WHITE
d[u] ∞
π [s] NIL
r
s
t
u
v
w
x
y
Q
s
Considering s as root node
color[s] GRAY
d[s] 0
π [s] NIL
ENQUEUE (Q, s)
r
s
t
u
0
v
w
x
y
Q
w
r
r
s
t
u
1
0
1
v
w
x
y
Q
r
t
x
r
s
t
u
1
0
2
1
2
v
w
x
y
Q
t
x
v
r
s
t
u
1
0
2
2
1
2
v
w
x
y
r
s
t
u
1
0
2
3
2
1
2
v
w
x
y
Q
x
v
u
DEQUEUE t from Q
Adj[t] = u, w, x
color [u] = WHITE
color [u] ← GRAY
d [u] ← d [t] + 1 = 2 + 1 = 3
π[u] ← t
ENQUEUE (Q, u)
color [w] ≠ WHITE
color [x] ≠ WHITE
color [t] ← BLACK
r
s
t
u
1
0
2
3
2
1
2
3
v
w
x
y
Q
v
u
y
DEQUEUE x from Q
Adj[x] = t, u, w, y
color [t] ≠ WHITE
color [u] ≠ WHITE
color [w] ≠ WHITE
color [y] = WHITE
color [y] ← GRAY
d [y] ← d [x] + 1 = 2 + 1 = 3
π[y] ← x
ENQUEUE (Q, y)
color [x] ← BLACK
r
s
t
u
1
0
2
3
2
1
2
3
v
w
x
y
Q
u
y
DEQUEUE v from Q
Adj[v] = r
color [r] ≠ WHITE
color [v] ← BLACK
r
s
t
u
1
0
2
3
2
1
2
3
v
w
x
y
Q
y
DEQUEUE u from Q
Adj[u] = t, x, y
color [t] ≠ WHITE
color [x] ≠ WHITE
color [y] ≠ WHITE
color [u] ← BLACK
r
s
t
u
1
0
2
3
2
1
2
3
v
w
x
y
Q
DEQUEUE y from Q
Adj[y] = u, x
color [u] ≠ WHITE
color [x] ≠ WHITE
color [y] ← BLACK
Breadth First Search
Total Running Time of BFS = O(V+E)
Shortest Paths
Shortest Paths