Presentation is loading. Please wait.

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

## Presentation on theme: "308-203A Introduction to Computing II Lecture 15: Searching Graphs II Fall Session 2000."— Presentation transcript:

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

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)

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)

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

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)?

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

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”

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

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

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

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

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

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

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

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

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)

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 )

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

Any questions?

Download ppt "308-203A Introduction to Computing II Lecture 15: Searching Graphs II Fall Session 2000."

Similar presentations

Ads by Google