This preview shows page 1. Sign up to view the full content.
Unformatted text preview: Progress? On every iteration one vertex is processed (turns gray). BFS(G,s)
Precondition: G is a graph, s is a vertex in G
Postcondition: d [u ] = shortest distance [u ] and
[u] = predecessor of u on shortest paths from s to each vertex u in G
for each vertex u V [G]
d [u ]
[u ] null
color[u] = BLACK //initialize vertex
colour[s]
RED
d [s ] 0
Q.enqueue(s )
while Q
u Q.dequeue()
for each v Adj[u ] //explore edge (u,v )
if color[v ] = BLACK
colour[v] RED
d [v ] d [u ] + 1 colour [u ]
CSE 2011
Prof. J. Elder [v ] u
Q.enqueue(v )
GRAY
 161  Last Updated: 4/1/10 10:16 AM Optimal Substructure Property
The shortest path problem has the optimal substructure property:
Every subpath of a shortest path is a shortest path. shortest path
How would we
prove this? v u s
shortest path shortest path The optimal substructure property
is a hallmark of both greedy and dynamic programming algorithms.
allows us to compute both shortest path distance and the shortest paths
themselves by storing only one d value and one predecessor value per
vertex.
CSE 2011
Prof. J. Elder  162  Last Updated: 4/1/10 10:16 AM Recovering the Shortest Path
For each node v, store predecessor of v in (v). s
u v (v) Predecessor of v is (v) = u. CSE 2011
Prof. J. Elder  163  Last Updated: 4/1/10 10:16 AM Recovering the Shortest Path CSE 2011
Prof. J. Elder  164  Last Updated: 4/1/10 10:16 AM BFS Algorithm without Colours
BFS(G,s)
Precondition: G is a graph, s is a vertex in G
Postcondition: predecessors [u] and shortest
distance d [u ] from s to each vertex u in G has been computed
for each vertex u V [G]
d [u ]
[u ] null
d [s ] 0
Q.enqueue(s )
while Q
u Q.dequeue()
for each v Adj[u ] //explore edge (u,v )
if d[v ] =
d [v ] d [u ] + 1
[v ] u
Q.enqueue(v )
CSE 2011
Prof. J. Elder  165  Last Updated: 4/1/10 10:16 AM ...
View
Full
Document
This note was uploaded on 02/14/2012 for the course CSE 2011Z taught by Professor Elder during the Fall '11 term at York University.
 Fall '11
 Elder
 Data Structures

Click to edit the document details