简体   繁体   中英

DFS on undirected graph complexity?

As when we traverse the undirected connected graph using DFS and mark out only edges which we travel during DFS, we end up with a DFS tree which is basically a tree and traversing a tree requires O(v) complexity where v is the number of vertices, then why it stated that complexity is O(v + e)?

I know it's a noob question but I am confused.

The DFS tree is the tree made of the edges you traversed . You indeed only traverse O(V) edges. But in order to traverse an edge, you first examine the edge to check if it will lead to a vertex you already encountered. This means you examine more edges than you traverse . Indeed, you examine O(E) edges. So the total work is O(V+E) .

Note: Because your graph is connected, you are sure that E > V . In that case the complexity can be rewritten O(E) .

you find all the nodes of graph through edges so the time complexity depends upon no. of edges as well that's why the O(e) is also included. If you consider complete graph TC will be O(V^2).

Consider two different graphs:

  1. A graph having more edges than vertices, for instance a connected graph with a high minimum degree .

    When the DFS algorithm visits a vertex, it will have to follow each of the edges that connect this vertex, repeating a DFS traversal from the neighboring vertices. Of course, if that neighbor was already visited, the DFS algorithm will backtrack, but at least we can state that the edge had to be processed.

    This procedure will process all edges of the graph. So in this case we can say the algorithm is O(e)

  2. A graph having fewer edges than vertices, often a disconnected graph (in the extreme case there are no edges).

    When the DFS algorithm has visited all vertices that it can reach from a traversal that started in vertex A, it must still iterate over the remaining vertices, to find vertices that might not have been visited. These unvisted vertices do not belong to the same connected component ). Another DFS traversal must start from there.

    This way all vertices are processed. So in this case the algorithm has a O(v) time complexity

So in general, the algorithm has a O(max(e, v)) time complexity. You could also say that the algorithm must visit all edges and all vertices, and so the algorithm has a O(e+v) time complexity. Both are equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM