Download presentation
Presentation is loading. Please wait.
Published byΠαρθενιά Λύτρας Modified over 5 years ago
1
Breadth-First Search L0 L1 L2 C B A E D F Breadth-First Search
4/18/2019 5:55 PM Breadth-First Search C B A E D L0 L1 F L2 Breadth-First Search
2
Breadth-First Search Breadth-first search (BFS) is a general technique for traversing a graph Similar to breadth-first traversal in trees “level by level” “children” -> “neighbors” Level is number of edges from the starting node Visit each node only once Breadth-First Search
3
Example unexplored vertex visited vertex unexplored edge
C B A E D L0 L1 F A unexplored vertex A visited vertex unexplored edge discovery edge cross edge L0 L0 A A L1 L1 B C D B C D E F E F Breadth-First Search
4
Example (cont.) L0 L1 L0 L1 L2 L0 L1 L2 L0 L1 L2 C B A E D F C B A E D
Breadth-First Search
5
Example (cont.) L0 L1 L2 L0 L1 L2 L0 L1 L2 C B A E D F A B C D E F C B
Breadth-First Search
6
BFS Algorithm Algorithm BFS(G, s)
Queue new empty queue enqueue(Queue, s) while Queue.isEmpty() v dequeue(Queue) if getLabel(v) != VISITED // ** visit v setLabel(v, VISITED) neighbors getAdjacentVertices(G, v) for each w neighbors if getLabel(w) != VISITED // “children” enqueue(Queue, w) The algorithm uses a mechanism for setting and getting “labels” of vertices and edges Container C in the book is a queue. ** An unexplored vertex might be might be put on the queue more than once After the first one is visited, the rest can be skipped. A queue doesn’t usually have an operation to find an entry on the queue What is another way to check if an entry is already on the queue? Hint: getLabel() Breadth-First Search
7
Analysis Setting/getting a vertex/edge label takes O(1) time Each vertex is labeled twice once as UNEXPLORED once as VISITED O(n) getAdjacentVertices(v) is called once for each vertex that is not visited Each edge in the graph is used at most twice Each edge has two vertices O(m) BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure [less precisely, since m is O(n2), BFS is also O(n2)] Breadth-First Search
8
Properties Notation Property 1 Property 2 Property 3 (not in DFS)
Gs: connected component of s Property 1 BFS(G, s) visits all the vertices and edges of Gs Property 2 The discovery edges labeled by BFS(G, s) form a spanning tree Ts of Gs Property 3 (not in DFS) For each vertex v in Li The path of Ts from s to v has i edges Every path from s to v in Gs has at least i edges A B C D E F L0 A L1 B C D L2 E F Breadth-First Search
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.