I know the answer to this particular question is O(V + E) and for a Graph like a tree, it makes sense because each Vertex is being explored once only.
However let’s say there is a cycle in the graph.
For example, let’s take up an undirected graph with four vertices A-B-C-D.
A is connected to both B and C, and Both B and C are connected to D. So there are four edges in total. A->B, A->C, B->D, C->D and vice versa.
Let’s do DFS(A).
It will explore B first and B’s neighbor D and D’s neighbor C. After that C will not have any edges so it will come back to D and B and then A.
Then A will traverse its second edge and try to explore C and since it is already explored it will not do anything and DFS will end.
But over here Vertex “C” has been traversed twice, not once. Clearly worst case time complexity can be directly proportional to V.
Any ideas?
If you do not maintain a
visitedset, that you use to avoid revisitting already visited nodes, DFS is notO(V+E). In fact, it is not complete algorithm – thus it might not even find a path if there is a one, because it will be stuck in an infinite loop.Note that for infinite graphs, if you are looking for a path from
stot, even with maintaining a visited set, it is not guaranteed to complete, since you might get stuck in an infinite branch.If you are interested in keeping DFS’s advantage of efficient space consumption, while still being complete – you might use iterative deepening DFS, but it will not trivially solve the problem if you are looking to discover the whole graph, and not a path to a specific node.
EDIT: DFS pseudo code with
visitedset.It is easy to see that you invoke the recursion on a vertex if and only if it is not yet visited, thus the answer is indeed linear in the number of vertices and edges.