Skip to content
Related Articles

Related Articles

Why is the complexity of both BFS and DFS O(V+E)?

Improve Article
Save Article
  • Last Updated : 20 Sep, 2022
Improve Article
Save Article

BFS and DFS are two algorithms that we use for graph traversal. In both the algorithms we start from a node and iterate over the whole graph with V nodes and E edges. Also, the time complexity of iterating over the graph with these traversal techniques is O(V + E).

Why is the complexity of iterating over the graph with these traversal techniques O(V+E)?

1) DFS:

While iterating with this technique, we move over each node and edge exactly once, and once we are over a node that has already been visited then we backtrack, which means we are pruning possibilities that have already been marked. So hence the overall complexity is reduced from exponential to linear.

Pseudocode for DFS:

DFS(Graph, vertex)
    vertex.visited = true
    for each v1 ∈ Graph.Adj[vertex]
        if v1.visited ==  false
            DFS(Graph, v1)
    

2) BFS:

In this technique, each neighboring vertex is inserted into the queue if it is not visited. This is done by looking at the edges of the vertex. Each visited vertex is marked visited once we visit them hence, each vertex is visited exactly once, and all edges of each vertex are checked. So the complexity of BFS is V + E

Pseudocode for BFS:

create a queue Q 

v.visited = true

Q.push(v)
while Q is non-empty 
   remove the head u of Q 
   mark and enqueue all (unvisited) neighbours of u

Since we are only iterating over the graph’s edges and vertices only once, hence the time complexity for both the algorithms is linear O(V+E).

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!