1

Consider the algorithm (from another question):

set start vertex to visited
load it into queue
    while queue not empty
        for each edge incident to vertex
             if its not visited
                 load into queue
                 mark vertex

The complexity of the algorithm is defined as the upper bound of times the inner loop can run, right? Well, considering a complete graph. For each one of its N vertexes, we run the check if its not visited N-1 times. So, that's N * (N-1) tests, which is quadratic. What is wrong with this view?

Raphael
  • 72,336
  • 29
  • 179
  • 389
Viclib
  • 73
  • 1
  • 1
  • 4

3 Answers3

2

Overall, BFS accesses (and processes) each edge constant times (twice actually; we assume an undirected graph), costing $O(E)$ total time in edge processing. Similarly, all the vertices are totally accessed (including queue operations and checking operations) $O(E) \cdot O(1)$ times. The overhead for initialization is $O(V)$. Thus the total running time of BFS is $O(V + E)$.

This can be viewed as a simple instance of aggregate analysis.

hengxin
  • 9,541
  • 3
  • 36
  • 73
0

Each vertex is visited once and each edge twice assuming implementation with an adjacency list so the running time is a constant multiple of the number of edges + number of vertices. Thus it is O(V + E).

mLstudent33
  • 207
  • 1
  • 7
-1

In BFS algorithm we begin from a arbitary vertex, so we meet all of vertexes then we claim that $O(v)$.since we must meet all vertexes then we used maximum edges to reach other vertexes . so we have $O(V+E)$

  • Welcome to Computer Science Stack Exchange! Unfortunately, I can't work out what your argument is, here. What do you mean by "then we used maximum edges to reach other vertices"? What if you got lucky and only looked at $V$ edges? How can you guarantee that edges won't be considered many times each? – David Richerby Dec 01 '14 at 10:41