Download presentation

Presentation is loading. Please wait.

Published byLenard Pierce Modified about 1 year ago

1
308-203A Introduction to Computing II Lecture 15: Searching Graphs II Fall Session 2000

2
Depth-First Search DFS-Visit(Vertex v) { v.setColor(grey); for each u in v.neighbors() if (u.color( ) == white) DFS-Visit(u); v.setColor(black); } (Assume all nodes start off colored white)

3
Running 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: T v = time for the “for” loop + constants = ( degree(v) ) + (1)

4
Running Time of DFS Total Time = v V [ T v ] = v V [ degree(v) + 1 ] = v V degree(v) + v V 1 = O( |E| + |V| )

5
Deficiencies 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 n th step before considering possible steps for (n+1)?

6
Breadth-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

7
Breadth-First Search BFS( Vertex startVertex ) { startVertex.setColor(grey); queue.enqueue( startVertex ); while (queue.hasMoreElements( )) { Vertex v = queue.dequeue( ); explore( v ); } Again, assume all vertices start of “white”

8
Breadth-First Search explore( Vertex v ) { forall u Neighbors( v ) if (u.color() == white) { u.setColor( grey ) ; queue.enqueue( u ); } v.setColor( black ); }

9
BFS - Example abc def Start by enqueueing “a” Queue = { a }

10
BFS - Example abc def Service “a” by calling explore( ) Queue = { b, d }

11
BFS - Example abc def Service “b” (“d ” remains in the queue) Queue = { d, e }

12
BFS - Example abc def Service “d”: no unexplored neighbors Queue = { e }

13
BFS - Example abc def Service “e”: enqueues “c” and “f” Queue = { c, f }

14
BFS - Example abc def Service “c”: no unexplored neighbors Queue = {f }

15
BFS - Example abc def Service “f”: now the queue is empty Queue =

16
BFS 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)

17
Comparison to DFS abc def abc def DFS BFS Visited: (a, b, e, d, [e], c, f, [c], [e], [b], [a]) Visited: ( a, b, d, e, c, f )

18
Running 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| )

19
Any questions?

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google