Single Source Shortest Path - DIJKSTRA'S Algorithm - Introduction and Code
Why do we need Dijkstra's Algorithm? We have seen that BFS can only be used to find the shortest path in unweighted graphs. So, for the weighted graphs, Dijkstra comes to our rescue. Dijkstra can be used for all 6 types of graphs. BUT, there is a scenario where DIJKSTRA's ALGORITHM CAN NOT BE USED : when a graph has a NEGATIVE CYCLE . So a path is called a 'Negative Cycle' if: a) There is a cycle (quite obvious, isn't it ?) b) The Total weight of the cycle should be a negative number. For example - for now, let's consider in the above graph, the weight of edge AD as -6 instead of +6. Now, if we see the path DBAD, it is a cycle and total weight = 1 + 3 - 6 = -2, that is negative weight. So, a negative cycle. So, what is the reason that Dijkstra's Algorithm fails for a negative cycle? For one more time let's consider in the above graph the weight of edge AD as -6 instead of +6. Now, we know Dijkstra finds the shortest path. If the graph has a negative...