110 likes | 252 Views
Is G connected?. Is there a path from vertex a to vertex b ? . Does G have a cycle? . Will removing a single edge disconnect G ?. If G is directed, what are the strongly connected components?. If G is the WWW, follow links to locate information. .
E N D
Is G connected? Is there a path from vertex a to vertex b? Does G have a cycle? Will removing a single edge disconnect G? If G is directed, what are the strongly connected components? If G is the WWW, follow links to locate information. Most graph algorithms need to examine or process each vertex and each edge. Graph Traversals Visit vertices of a graph G to determine some property:
the distance of each vertex from s. a tree of shortest paths called thebreadth-first tree. Breadth-First Search Find the shortest path from a source node s to all other nodes. Outputs Idea: Find nodes at distance 0, then at distance 1, then at distance 2, …
L = s 0 A BFS Example b s e c g f a d
L = s 0 L = a, c frontier of exploration 1 b s e c g f a d Visualized as many simultaneous explorations starting from s and spreading out independently.
L = s 0 L = d, e, f 2 b s e c g f a d Dashed edges were explored but had resulted in the discovery of no new vertices. L = a, c 1
L = s 0 L = d, e, f L = b, g 2 3 b s e c g f a d L = a, c 1
L = s 0 L = d, e, f L = b, g 3 2 The Finish b s e c g f a d L = a, c 1
b d(b): shortest distance from s to b s e c g f a d Breadth-First Tree 3 0 2 3 1 2 1 2 # visited vertices = 1 + # tree edges 1 + # explored edges.
The BFS Algorithm BFS(G, s) for eachv V(G) – sdo d(v) // shortest distance from s d(s) 0 // initialization L s T i 0 whileL ≠ do // all nodes at distance i from s L for eachu Ldo for eachv Adj(u) do ifd(v) = then // not yet visited d(v) d(u) + 1 insert v into L T T {(u, v)} i i + 1 0 i i+1 i i+1
Basis: L = s includes the only node at distance 0 from s. 0 Inductive step: Suppose L consists of all nodes at distance k≥ 0 from s. k k … s u v By hypothesis u L . Thus v L . k k+1 Correctness LemmaFor each i, the set L includes all nodes at distance i from s. i Proof By induction on the distance k from s. Every node v at distance k+1 from s must be adjacent to a node u at distance k. Corollary At the finish of BFS, d(v) is the length of the shortest path from s to v.
Every vertex is inserted at most once into some list L . i # edge scans u e ≤ |E| for a directed graph v ≤ 2 |E| for an undirected graph e v u 2 O(|V| )if represented as an adjacency matrix. Running Time O(|E|)if G is represented using adjacency lists. # inserted vertices 1 + # scanned edges |E| + 1. Courtesy of Dr. Fernandez-Baca