Sunday, August 4, 2013

Why is DFS O(m+n)

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

Then the sum
v1 + (incident edges) + v2 + (incident edges) + .... + vn + (incident edges)
can be rewritten as
(v1 + v2 + ... + vn) + [(incident_edges v1) + (incident_edges v2) + ... + (incident_edges vn)]
and the first group is O(N) while the other is O(E).

No comments:

Post a Comment