I am trying to understand how/why complexity of DFS is O(V+E). Here is my attempt at analysing complexity of pseudo-code iterative DFS.
DFS(G, t)
{
1 stack S = new empty Stack of size G.|V| ... O(1)
2 S.push(t) ... O(1)
3 while(S is not Empty) ... O(|V|), this will always be =<|V|
{
4 u = S.pop() ... O(1)
5 if(u.visited = false) ... O(1)
{
6 u.visited = true ... O(1)
7 for-each edge (u,v) in G.E ... O(|E|), this will always be =<|E|
8 if(v.visited = false) ... O(1)
9 S.push(v) ... O(1)
}
}
}
Now combining complexity of each line we have:
O(1) + O(1) + O(|V|)[O(1) + O(1) + O(1) + O(E)[O(1) + O(1)]] = O(2) + O(V) + O(V) + O(V) + O(V) + O(V * E) + O(V * E) = 4*O(V) + 2*O(V * E) = O(V * E)
I did not get O(V+E)? Can anyone show me mathematically how we achieve O(V+E)?
Can anyone provide insight?