0

I've been practicing various algorithms and I just completed Dijkstra's algorithm to calculate the shortest distance between nodes on a graph. After completing the exercise leveraging an indexed minHeap, I also completed it leveraging BFS (solution attached). Which leads me to a couple of questions:

  1. If my calculation for time complexity is correct - I've calculated the complexity of the attached solution to be O(v^2 + e) where V = the number of vertices and E = the number of edges. We iterate and touch each node once and only once, same for the edges. The v^2 comes from the shift operation since this happens on every iteration.
  2. This BFS solution could be improved by leveraging something similar to an ArrayDeque in Java, this would give us O(1) operations everytime we pop off the front of the queue, and should reduce our time complexity down to O(v+e)
  3. If the above is true, what are the advantages or use-cases for leveraging Dijkstra's algorithm as opposed to BFS. It seems that BFS would have a better time complexity (O(V+E)) than Dijkstra's O((V+E)*log(V)), and will protect against the case of negative cycles where as Dijkstra's will fall into an infinite loop in this case.

Sample input:

edges = [[[1, 7]], [[2, 6], [3, 20], [4, 3]], [[3, 14]], [[4, 2]], [], []],

start = 0

shortest distance - breadth first search

Rich EBee
  • 104
  • 6

1 Answers1

0

BFS and Dijkstras algorithm compute two different things that are only in some cases the same.

Given a starting node s

  • BFS computes the shortest paths to all other nodes in terms of hops / the number of edges.
  • Dijkstras algorithm computes the shortest paths to all other nodes in terms of edge weights.

This are two different things but in some cases they are the same, e.g.

  • the graph is a tree (there is only one path between any given pair of nodes)
  • all edge weights are equal (or the graph is unweighted).

Dijkstras algorithm has a time complexity of O(|V| log |V| + |E|) if implemented using Fibonacci-heaps, while BFS has a time complexity of O(|V| + |E|).

So you are correct that BFS might be a good choice if your input allows you to choose between them. However, in practice you might want to do some benchmarks first on real world data.

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66