Explanation of runtimes of BFS and DFS

后端 未结 5 451
你的背包
你的背包 2021-01-30 08:42

Why are the running times of BFS and DFS O(V+E), especially when there is a node that has a directed edge to a node that can be reached from the vertex, like in this example in

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 09:36

    This issue consumed like 4 hours of my time but finally, I think I have an easy way to get the picture, at the beginning I was tempted to say O ( V * E ).

    Summarizing the algorithm that you find in Cormen, that is the same on http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/breadthSearch.htm you have something like this :

    for (vi in V)
    {
       Some O(1) instructions
       for ( e in Adj(vi) ) {
          Some O(1) instructions
       }
    }
    

    The question is how many instructions are executed here? that will be the Sigma-Sum (Adj(vi)), and this value is upper-bounded by 2|E|.

    In the beginning, we automatically think about multiplying the number of iterations of the inner and outer loops, but in this case, the total number of iterations on the inner loop is a function of the outer iterator, so no multiplication is possible.

提交回复
热议问题