Why does the time complexity of DFS and BFS depend on the way the graph is represented?

后端 未结 3 1461
予麋鹿
予麋鹿 2021-01-30 14:46

The site http://web.eecs.utk.edu/~huangj/CS302S04/notes/graph-searching.html describes that when an adjacency list is used then, DFS and BFS have complexity O(V+E), and if an ad

3条回答
  •  耶瑟儿~
    2021-01-30 15:14

    The time complexity for both DFS and BFS can be computed as follows:

    Iterating every vertex once and its corresponding incident edges, so the total time complexity will be ->

    Time Complexity = v1 + (incident_edges on v1) + v2 + (incident_edges on v2) + ...... + vn + ( incident_edges on vn)

    Now this can be regrouped as -> (v1+v2+v3+.....vn) + (incident_edges on v1 + incident_edges on v2 + ..... incident_edges on vn)

    Thus total time complexity would turn out to be = (v1+v2+v3+.....vn) + (incident_edges on v1 + incident_edges on v2 + ..... incident_edges on vn)

    (v1 + v2 + ... + vn) = V or n (Total number of vertices)

    For adjacency list representation :

    (incident_edges on v1 + incident_edges on v2 + ..... incident_edges on vn) = E(Total number of edges)

    Thus for adjacency list representation time complexity will be O(V+E)

    For adjacency matrix representation :

    To visit the neighbors of the corresponding node(Row) we need to iterate all the columns for the particular row which amounts to V

    So, (incident_edges on v1 + incident_edges on v2 + ..... incident_edges on vn) = V + V + .... Vth time V) = V*V

    Thus time complexity will be O(V + V^2) = O(V^2)

提交回复
热议问题