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.


shortest and 2nd shortest dijkstra

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

JavaScript

Python

Output:
shortest path: [2, 1, 0, 3]
Shortest distance: 3
2nd shortest distance: 5

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.


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

Comments are closed