Skip to content

Instantly share code, notes, and snippets.

@neilharia7
Last active February 10, 2017 18:31
Show Gist options
  • Save neilharia7/735aee0ed46677e665f0 to your computer and use it in GitHub Desktop.
Save neilharia7/735aee0ed46677e665f0 to your computer and use it in GitHub Desktop.
Dijkstra's shortest path code in java which gives shortest route to all other paths
/*
Dijkstra's Shortest Path Algorithm
The following program gives the shortest path from the source to all other nodes
*/
import java.util.*;
import java.io.*;
class DijkstrasAlgorithm{
public static void main(String args[]){
int array[][];
int i,j,n,s;
int INFINITY = 99999;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices :");
n = sc.nextInt();
array = new int[n+1][n+1];
for(i= 1;i<= n;i++){
for(j= 1;j<= n;j++){
System.out.println("Enter 0 if "+i+" has a node with "+j+" else 1 :");
array[i][j] = sc.nextInt();
}
}
System.out.println("Intial Matrix is :");
for(i= 1;i<= n;i++){
for(j= 1;j<= n;j++){
if(array[i][j] == 1){
array[i][j] = INFINITY;
System.out.print(" "+array[i][j]+" ");
}
else if(array[i][j] == 0){
System.out.print(" "+array[i][j]+" ");
}
}
System.out.println();
}
System.out.println(" Enter the Weighted Matrix");
for(i= 1;i<= n;i++){
for(j= 1;j<= n;j++){
array[i][j] = sc.nextInt();
if(i == j){
array[i][j] = 0;// to remove the self loop nodes if any
continue;
}
if(array[i][j] == 0){
array[i][j] = INFINITY;
}
}
}
System.out.println("Enter the Starting point :");
s = sc.nextInt();
if(s == 0 || s > n){
System.out.println("Invalid Address");
}
shortestPathFinder(array, n, s, INFINITY);
}
public static void shortestPathFinder(int[][] array, int n, int s, int INFINITY){
/*shortestPathFinder method needs to static since non static method cannot
be referenced from a static method*/
int cost[][] = new int[n+1][n+1];
int distance[] = new int[n+1];
int previous[] = new int[n+1];
int visited[] = new int[n+1];
int count,nextNode=1,minimumDistance,i,j;
for(i= 1;i<= n;i++){
for(j= 1;j<= n;j++){
if(array[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = array[i][j];
}
}
for(i= 1;i<= n;i++){
distance[i]=cost[s][i];
previous[i]=s;
visited[i]=0;
}
distance[s]=0;
visited[s]=1;
count=1;
while(count<n-1){
minimumDistance=INFINITY;
for(i=1;i <= n;i++)
if(distance[i] < minimumDistance&&(visited[i]==0)){
minimumDistance=distance[i];
nextNode=i;
}
visited[nextNode]=1;
for(i=1;i <= n;i++){
if(visited[i]==0)
if(minimumDistance+cost[nextNode][i] < distance[i]){
distance[i]=minimumDistance+cost[nextNode][i];
previous[i]=nextNode;
}
}
count++;
}
for(i=1;i <= n;i++){
if(i!=s){
System.out.println("Distance to "+i+" from source "+s+" is "+distance[i]);
System.out.print("Path followed = "+i);
j=i;
do{
j=previous[j];
System.out.print(" <- "+j+" ");
}
while(j!=s);
System.out.println();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment