Shortest path and 2nd shortest path using Dijkstra – code

What is Dijkstra’s algorithm? Dijkstra’s algorithm is an algorithm to find the shortest paths between vertices in a graph. It uses greedy technique by picking the un-visited vertex with the lowest distance. When all vertices have been evaluated, the result is the shortest path.

Find 2nd shortest path is a Find kth problem. It can be achieved by using K_shortest_path_routing or Yen’s_algorithm. Here I introduce a simple approach to find shortest path and 2nd shortest path using Dijkstra. The steps are: first find the shortest path using dijkstra. Second, remove each edge in the shortest path. Now find the shortest path again. Finally compare and return the shortest path among them as the second shortest path from source to destination.

Please note, In this implementation, the graph is un-directed, and represented as matrix.

Amazon Interview Question (CareerCup):
You are given a graph and an algorithm that can find the shortest
path between any two nodes
Now you have to find the second shortest path between same two nodes.

Java Code:

Output:
Shortest:6
2nd shortest:8

O Notation:
Time complexity: O(n^2)
Space complexity: O(n)

Note:
If you have any questions or want to put comments, please post at youtube. I will answer you!

Action Items:
Download ShortestPathAnd2ndShortestDijkstras.java
Find shortest and 2nd shortest path using Dijkstra tutorial
The complete list of coding interview questions

Comments are closed