The basic algorithm for BFS:
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
So I would think the time complexity would be:
v1 + (incident edges) + v2 + (incident edges) + .... + vn + (incident edges)
where v
is vertex 1
to n
Firstly, is what I've said correct? Secondly, how is this O(N + E)
, and intuition as to why would be really nice. Thanks
Time complexity is
O(E+V)
instead ofO(2E+V)
because if the time complexity is n^2+2n+7 then it is written as O(n^2).Hence, O(2E+V) is written as O(E+V)
because difference between n^2 and n matters but not between n and 2n.
I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).
Very simplified without much formality: every edge is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices.
An intuitive explanation to this is by simply analysing a single loop:
So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives
[ O(1) + O(e)]
DFS(analysis):
O(1)
timeO(n + m)
time provided the graph is represented by the adjacency list structureΣv deg(v) = 2m
BFS(analysis):
Li
O(n + m)
time provided the graph is represented by the adjacency list structureΣv deg(v) = 2m
Short but simple explanation: