Which algorithm do I use and how much does it cost if I have to:

Calculate all distances in an undirected and unweighted graph from two sources to all nodes.

I think the most appropriate algorithm is a BFS(G,s) with cost T(n)= O(V+E) where V= (number of nodes) and E=(number of arcs). The algorithm is the one in the figure. In this algorithm, however, only one source is considered. So it wouldn't answer the question. What would be the right answer and what the cost?

enter image description here

  • $\begingroup$ Hint: if $f(n,m)$ is a positive function, then $2\cdot f(n,m) = O(f(n,m))$. $\endgroup$
    – Steven
    Feb 19 at 11:27

1 Answer 1



  1. Run $BFS(vertex_{1})$.
  2. Run $BFS($vertex_{2})$.


$O(|V|+|E|) + O(|V|+|E|) = O(|V|+|E|)$

As long as you have a constant $c$, then $c\times f(n) = O(f(n)) $.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.