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

The complexity of both BFS and DFS are O(V+E) because every vertex (V) and every edge (E) is explored only once.

In graph theory, two fundamental algorithms used for traversing or searching tree or graph data structures are Breadth-First Search (BFS) and Depth-First Search (DFS). Let’s look at Why is the complexity of both BFS and DFS is O(V+E).

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

1) DFS Traversal:

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)

The time complexity of DFS is also O(V+E) due to:

  1. It visits each vertex once, contributing V to the complexity.
  2. It checks each edge once when moving from one vertex to its adjacent vertices, contributing E to the complexity.

2) BFS Traversal:

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).

The time complexity of BFS is O(V+E) because:

  1. It visits each vertex once, contributing V to the complexity.
  2. It checks each edge once when moving from one vertex to its adjacent vertices, contributing E to the complexity.

Conclusion

The time complexity of BFS and DFS is O(V+E) because it need to visit and examine every vertex and edge in the graph. This makes them linear algorithms, which are generally efficient for graph traversal.




Reffered: https://www.geeksforgeeks.org


Analysis Of Algorithms

Related
Potential Method in Amortized Analysis Potential Method in Amortized Analysis
Prove Max2SAT is NP-Complete by Generalisation Prove Max2SAT is NP-Complete by Generalisation
Why do we check up to the square root of a number to determine if that number is Prime? Why do we check up to the square root of a number to determine if that number is Prime?
Minimum Difference between multiples of three integers Minimum Difference between multiples of three integers
Prove that Sparse Graph is NP-Complete Prove that Sparse Graph is NP-Complete

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13