The time complexity for DFS and BFS can be calculated as follows:
Iterate over each vertex once and the corresponding incident edges , so the total time complexity will be ->
Time complexity = v1 + (incident_edge on v1) + v2 + (incident_bound on v2) + ...... + vn + (incident_bound on vn)
Now it can be rearranged as β (v1 + v2 + v3 + ..... vn) + (incident_ji on v1 + incident_ji on v2 + ..... incident_ji on vn)
Thus, the total complexity of the time would be = (v1 + v2 + v3 + ..... vn) + (incident_ji on v1 + incident_ji on v2 + ..... incident_ji on vn)
(v1 + v2 + ... + vn) = V or n (total number of vertices)
To represent an adjacency list :
(hedge incident on v1 + hedge incident on v2 + ..... hedge incident on vn) = E (total number of edges)
Thus, for the adjacency list presentation time, the time complexity will be O (V + E)
To represent an adjacency matrix :
To visit the neighbors of the corresponding node (row), we need to iterate over all the columns for a particular row, which is V
So, (incident_edge on v1 + incident_edge on v2 + ..... incident_edge on vn) = V + V + .... Vth time V) = V * V
So the time complexity will be O (V + V ^ 2) = O (V ^ 2)
Vimal kumar
source share