29 - 04/05/09 22:43:28 CS 61B: Lecture 29 Monday, April 6,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
04/05/09 22:43:28 1 29 CS 61B: Lecture 29 Monday, April 6, 2009 GRAPHS (continued) ====== Breadth-first search (BFS) is a little more complicated than depth-first search, because it’s not naturally recursive. We use a queue so that vertices are visited in order according to their distance from the starting vertex. public void bfs(Vertex u) { u.visit(null); // Do some unspecified thing to u u.visited = true; // Mark the vertex u visited q = new Queue(); // New queue. .. q.enqueue(u); // . ..initially containing u while (q is not empty) { v = q.dequeue(); for (each vertex w such that (v, w) is an edge in E) { if (!w.visited) { w.visit(v); // Do some unspecified thing to w w.visited = true; // Mark the vertex w visited q.enqueue(w); } } } } Notice that when we visit a vertex, public class Vertex { we pass the edge’s origin vertex protected Vertex parent; as a parameter. This allows us to protected int depth; do a computation such as finding the distance of the vertex from public void visit(Vertex origin) { the starting vertex, or finding this.parent = origin; the shortest path between them. if (origin == null) { The visit() method at right this.depth = 0; accomplishes both these tasks. } else { this.depth = origin.depth + 1; } } } When an edge (v, w) is traversed to visit a Vertex w, the depth of w is set to the depth of v plus one, and v is set to be the _parent_ of w. The sequence of figures below shows BFS running on the city adjacency graph (Albany, Kensington, Emeryville, Berkeley, Oakland, Piedmont) from last lecture, starting from Albany. A "V" is currently visited; a digit shows the depth of a vertex that is marked visited; a "*" is a vertex which we try to visit but discover has already been visited. Underneath each figure of the graph, I depict the queue and the current value of the variable "v" in bfs(). V-K
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 2

29 - 04/05/09 22:43:28 CS 61B: Lecture 29 Monday, April 6,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online