Question

A friend told me that breadth-first search algorithm (graph represented by the adjacency list) has a quadratic time complexity. But in all the sources says that the complexity of BFS algortim exactly O (|V| + |E|) or O (n + m), from which we obtain a quadratic complexity ?

Was it helpful?

Solution

All the sources are right :-) With BFS you visit each vertex and each edge exactly once, resulting in linear complexity. Now, if it's a completely connected graph, i.e. each pair of vertices is connected by an edge, then the number of edges grows quadratic with the number of vertices:

|E| = |V| * (|V|-1) / 2

Then one might say the complexity of BFS is quadratic in the number of vertices: O(|V|+|E|) = O(|V|^2)

OTHER TIPS

BFS is O(E+V) hence in terms of input given it is linear time algorithm but if vertices of graph are considered then no of edges can be O(|V|^2) in dense graphs hence if we consider time complexity in terms of vertices in graph then BFS is O(|V|^2) hence can be considered quadratic in terms of vertices

O(n + m) is linear in complexity and not quadratic. O(n*m) is quadratic. 0. Initially all the vertices are labelled as unvisited. We start from a given vertex as the current vertex. 1. A BFS will cover (visit) all the adjacent unvisited vertices to the current vertex queuing up these children. 2. It would then label the current vertex as 'visited' so that it might not be visited (queued again). 3 BFS would then take out the first vertex from the queue and would repeat the steps from 1 till no more unvisited vertices remain.

The runtime for the above algorithm is linear in the total no. of vertices and edges together because the algorithm would visit each vertex once and check each of its edges once and thus it would take no. of vertices + no. of edges steps to completely search the graph

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top