Why is the time complexity O(V+E) in depth-first search of graphs implemented as linked lists?

Asked 2 years ago, Updated 2 years ago, 44 views

           A
         / | \
        B  |  D -- E
         \ | /     |
           C ------+

If you have a graph implemented as a linked list, you must call the DFS function n times to visit n vertices, and each call must move between nodes in the linked list at least a certain number of times to find the next vertex to visit.

If the number of times this node moves is m, the time complexity should be O(nm).In practice, O (V+E) is the number of vertices V plus the number of edges E.

How was O(V+E) calculated?

algorithm

2022-09-22 20:20

1 Answers

The number of nodes N = the number of vertices V, and the number of movements is the number of edges, so O(V+E). O(nm) means that the loops of n and m are overlapped.


for(int i=0; i<N; i++)
{
    for(int j=0; j<M; j++)
    {
       // // do something
    }
 }


2022-09-22 20:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.