Title: 308203A Introduction to Computing II Lecture 15: Searching Graphs II
1308-203AIntroduction to Computing IILecture
15 Searching Graphs II
Fall Session 2000
2Depth-First Search
(Assume all nodes start off colored white)
DFS-Visit(Vertex v) v.setColor(grey)
for each u in v.neighbors() if (u.color( )
white) DFS-Visit(u) v.setColor(black)
3Running Time of DFS
For a connected graph G (V, E), DFS-Visit will
be called exactly once per vertex. When called
for a vertex v ? V, the time taken is Tv
time for the for loop constants ?(
degree(v) ) ?(1)
4Running Time of DFS
Total Time ?v ? V Tv ?v ? V
degree(v) 1 ?v ? V degree(v) ?v ? V
1 O( E V )
5Deficiencies of DFS
DFS explores a single path until it hits a cycle
and then backtracks this was observed to
be stupid for some examples, like graphs
representing games. What if we take the other
extreme and always fully explore the nth step
before considering possible steps for (n1)?
6Breadth-First Search (BFS)
- Maintain a queue of vertices to explore
- Service the queue by exploring that vertex
- When exploring a vertex, queue up any unexplored
- neighbors
7Breadth-First Search
Again, assume all vertices start of white
BFS( Vertex startVertex ) startVertex.setColo
r(grey) queue.enqueue( startVertex )
while (queue.hasMoreElements( )) Vertex v
queue.dequeue( ) explore( v )
8Breadth-First Search
explore( Vertex v ) forall u ? Neighbors( v
) if (u.color() white)
u.setColor( grey ) queue.enqueue( u )
v.setColor( black )
9BFS - Example
Start by enqueueing a
a
b
c
d
e
f
Queue a
10BFS - Example
Service a by calling explore( )
a
b
c
d
e
f
Queue b, d
11BFS - Example
Service b (d remains in the queue)
a
b
c
d
e
f
Queue d, e
12BFS - Example
Service d no unexplored neighbors
a
b
c
d
e
f
Queue e
13BFS - Example
Service e enqueues c and f
a
b
c
d
e
f
Queue c, f
14BFS - Example
Service c no unexplored neighbors
a
b
c
d
e
f
Queue f
15BFS - Example
Service f now the queue is empty
a
b
c
d
e
f
Queue ?
16BFS and trees
- Like DFS this can be thought of as inducing
- a tree (with edges from any node u to
- each other node v which it enqueues)
17Comparison to DFS
a
b
c
DFS
d
e
f
Visited (a, b, e, d, e, c, f, c, e, b,
a)
a
b
c
BFS
d
e
f
Visited ( a, b, d, e, c, f )
18Running time of BFS?
- Same as for DFS for exactly the same reason!
- Every node gets enqueued, and therefore
- explored exactly once
- In explore, there is a loop over all adjacent
- vertices, giving the same O( degree(v) ) term
- ? O( V E )
19Any questions?