Time complexity of depth-first graph algorithm

Learner picture Learner · Apr 12, 2012 · Viewed 56.8k times · Source

I am starting to learn time complexity, and I looked in the examples for the time complexity for some simple sort.

I wanted to know how do we calculate average time complexity for a depth-first search in a graph with |V|=n and |E|=m,let the start node be 'u' and end node be 'v'.

Answer

gabitzish picture gabitzish · Apr 12, 2012

The time complexity for DFS is O(n + m). We get this complexity considering the fact that we are visiting each node only once and in the case of a tree (no cycles) we are crossing all the edges once.

For example, if the start node is u, and the end node is v, we are thinking at the worst-case scenario when v will be the last visited node. So we are starting to visit each the first neighbor's of u connected component, then the second neighbor's connected component, and so on until the last neighbor's connected component, where we find v. We have visited each node only once, and didn't crossed the same edge more than once.