Professional Documents
Culture Documents
an edge (u,v)
Adjacency matrix
3 3 2 4
5 4 4 2 5 3 /
5 4 1 2
Undirected graph
MA512: Data Structures and Algorithms
12
Adjacency list for directed graph
• Sum of “lengths” of all adjacency lists
Directed graph: E
• edge (u, v) appears only once (in the list of u)
Undirected graph: 2 E
• edge (u, v) appears twice (in the lists of both u and v)
given node.
• Disadvantage
No quick way to determine whether there is an edge
r s t u
0 10 while Q
11 do u dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v] gray
15 d[v] d[u] + 1
16 [v] u
v w x y 17 enqueue(Q,v)
18 color[u] black
Q: s
0
(Courtesy of Prof. Jim Anderson)
Example (BFS)
r s t u
1 0 10 while Q
11 do u dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v] gray
1 15 d[v] d[u] + 1
16 [v] u
v w x y 17 enqueue(Q,v)
18 color[u] black
Q: w r
1 1
Example (BFS)
r s t u
1 0 10 while Q
11 do u dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v] gray
1 15 d[v] d[u] + 1
16 [v] u
v w x y 17 enqueue(Q,v)
18 color[u] black
Q: w r
1 1
Example (BFS)
r s t u
1 0 2 10 while Q
11 do u dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v] gray
1 2 15 d[v] d[u] + 1
16 [v] u
v w x y 17 enqueue(Q,v)
18 color[u] black
Q: r t x
1 2 2
Example (BFS)
r s t u
1 0 2 10 while Q
11 do u dequeue(Q)
12 for each v in Adj[u]
13 do if color[v] = white
14 then color[v] gray
1 2 15 d[v] d[u] + 1
16 [v] u
v w x y 17 enqueue(Q,v)
18 color[u] black
Q: r t x
1 2 2
Example (BFS)
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
2 2 2
Example (BFS)
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
2 2 3
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
2 3 3
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
3 3
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
3
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q:
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
E ={([v],v)E : v V - {s}}
r s t u
1 0 2 3
2 1 2 3
v w x y
MA512: Data Structures and Algorithms
38
Breadth First Tree
• For a graph G = (V, E) with source s, the predecessor
subgraph of G is G = (V , E) where
V ={vV : [v] NIL}{s}
E ={([v],v)E : v V - {s}}
[t]=w [u]=t
r s t u
[r]=s 1 0 2 3
[v]=r 2 1 2 3
v w x y
MA512: Data Structures and Algorithms
39
Breadth First Tree
• The predecessor subgraph G is a breadth-first tree
if:
V consists of the vertices reachable from s and
for all vV , there is a unique simple path from s to v in G
that is also a shortest path from s to v in G.
• The edges in E are called tree edges.
|E | = |V | - 1.
Analysis of Algorithms
41