Analysis of breadth-first search

How long does breadth-first search take for a graph with vertex set VV and edge set EE? The answer is O(V+E)O(V+E) time.

Let's see what O(V+E)O(V+E) time means. Assume for the moment that EV|E| \geq |V|, which is the case for most graphs, especially those for which we run breadth-first search. Then V+EE+E=2.E|V| + |E| \leq |E| + |E| = 2 . |E|. Because we ignore constant factors in asymptotic notation, we see that when EV|E| \geq |V|O(V+E)O(V+E) really means O(E)O(E). If, however, we have E<V|E| \lt |V|, then V+EV+V=2.V|V| + |E| \leq |V| + |V| = 2 . |V|, and so O(V+E)O(V+E) really means O(V)O(V). We can put both cases together by saying that O(V+E)O(V+E) really means O(max(V,E))O(max(V,E)). In general, if we have parameters xx and yy, then O(x+y)O(x + y) really means O(max(x,y))O(max(x, y)).

Note: A graph is connected if there is a path from every vertex to all other vertices. The minimum number of edges that a graph can have and still be connected is V1|V|−1. A graph in which E=V1|E| = |V|−1 is called a free tree.)

How is it that breadth-first search runs in O(V+E)O(V+E) time? It takes O(V)O(V) time to initialize the distance and predecessor for each vertex Θ(V)\Theta(V) time, actually). Each vertex is visited at most one time, because only the first time that it is reached is its distance null, and so each vertex is enqueued at most one time. Since we examine the edges incident on a vertex only when we visit from it, each edge is examined at most twice, once for each of the vertices it's incident on. Thus, breadth-first search spends O(V+E)O(V+E) time visiting vertices.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy