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.

In the following 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:
I have the tutorial of this interview question at youtube. Please leave your questions or comments in YouTube.

Grokking Algorithms has detailed illustrated explanation of Dijkstra algorithm. It gives step by step changes in the graph nodes and help you understand. Make sure to check it out!


Download ShortestPathAnd2ndShortestDijkstras.java
Find shortest and 2nd shortest distance in graph (YouTube)
Java Coding Interview Pocket Book (2nd Edition)

Comments are closed