BreadthFirstSearch

ClassS04CS141 | recent changes | Preferences

Difference (from prior minor revision) (no other diffs)

Changed: 28,29c28,38
Prove that BFS runs in time O(N+M)
on any graph with N vertices and M edges.
Upper bounds on its running time:
* O(n2) because the outer loop executes at most \
n times, and each time the inner loop executes, it executes \
at most n times.
* O(n+m) because the time can be counted as vertices w 1+degree(w) = n+2m . \
Here n is the number of vertices and m is the number of edges.

O(n+m) is linear in the input size, because encoding the graph takes Θ(n+m) space.

Algorithms that run in time linear in the input size are often the best possible,
because for many problems, any algorithm must at least examine the entire input.


Changed: 33c42
* GoodrichAndTomassia section 6.3.3.
* GoodrichAndTomassia section 6.3.3.

Breadth-first search

DFS is called "depth first" because it descends into the graph as quickly as possible.

Breadth-search first, in contrast, explores nodes by following a "wave front". It explores in order of their distance from the start vertex.

BFS(graph G, vertex v)

   FIFO_Queue Q;
   Array<int> distance(-1);
   
   distance[v] = 0;
   insert vertex v into the queue Q.

   while (Q is not empty)
      take the next vertex W off the front of the queue Q
      for each neighbor X of W do
         if (distance[X] == -1) then
            distance[X] = distance[W] + 1
            add vertex X to the tail of the queue Q
end

(example here)

Upper bounds on its running time:

O(n+m) is linear in the input size, because encoding the graph takes Θ(n+m) space.

Algorithms that run in time linear in the input size are often the best possible, because for many problems, any algorithm must at least examine the entire input.


References


ClassS04CS141 | recent changes | Preferences
This page is read-only | View other revisions
Last edited May 4, 2004 8:06 pm by Neal (diff)
Search: