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:
- 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.
- 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)
- 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