No, O (|V| + |E|)
is not equivalent to O (|V|^2)
.
Here's why.
Basically, if O(V+E) is linear time such that V+E = n, wouldn't O(V^2) also be linear time?
Perhaps this assumes that the graph is somehow given explicitly, we have to receive it as input in order to be able to work with it, and the total input size of edges is O (|V| + |E|) = n
.
But we don't always have to receive the input once, then run an algorithm once.
In some cases, we receive the input graph and then run the algorithm many times, so we are interested in its complexity regardless of the input size.
In some other cases, the graph is given implicitly, so the input does not take much time.
Example: consider the knight's graph on a k * k
chessboard: the graph where vertices are chessboard squares and edges are knight's moves.
An example problem to solve is this: given two squares, find the knight's path between them which is shortest in the number of moves.
An obvious algorithm to solve the problem is breadth-first search which takes O (|V| + |E|)
time
(we can do better but that's beside the point.)
Here, the input has size O (1)
: it's just the size of the board, k
, and coordinates of two squares on it.
We don't have to read or explicitly construct the graph at any time: it is given implicitly by the size k
.
In each vertex, we can enumerate all (up to 8) edges from this vertex in O (1)
.
In terms of k
, |V| = O (k)
, |E| <= 8 k
so |E| = O (k)
, so we also have O (|V| + |E|) = O (k)
.
On the other side, O (|V|^2) = O (k^2)
which is a looser bound than O (k)
.
Consequently, in this example, O (|V| + |E|)
is different from O (|V|^2)
, so they are generally not equivalent.
O(V^99)
also properly upper-bound the alghoritm, but this is not what you actually want to know. – Paddock