0% found this document useful (0 votes)
8 views2 pages

Dijk Stra

Daa vtu sem 4

Uploaded by

challalokesh4211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Dijk Stra

Daa vtu sem 4

Uploaded by

challalokesh4211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

PROGRAM 6:

Design and implement a Java program to find optimal road routes by using the Single
Source Shortest Path algorithm to find the shortest path from the source city to
all other cities.

import java.util.Scanner;

public class SSSP


{
static int[][] cost;
static int dist[],n;

static int min(int m, int n)


{
return(( m > n) ? n: m);
}

static void Dijkstra(int source)


{
int[] s=new int[n];
int min, w=0;
System.arraycopy(cost[source], 0, dist, 0, n);
//Initialize dist from source to source as 0
//mark source vertex - estimated for its shortest path
s[source] = 1; dist[source] = 0;
for(int i=0; i < n-1; i++)
{
//Find the nearest neighbour vertex
min = 999;
for(int j = 0; j < n; j++)
if ((s[j] == 0 ) && (min > dist[j]))
{
min = dist[j];
w = j;
}
s[w]=1;
//Update the shortest path of neighbour of w
for(int v=0;v<n;v++)
if(s[v]==0 && cost[w][v]!=999)
{
dist[v]= min(dist[v],dist[w]+cost[w][v]);
}
}
}

public static void main(String[] args)


{
int source;
Scanner s=new Scanner(System.in);

System.out.println("Enter the no.of vertices");


n = s.nextInt();
cost = new int[n][n];
dist = new int[n];

//Enter the cost matrix, 0 for principle diagnol axis


//999 for no direct edge from i to j
System.out.println("Enter the cost matrix");
for(int i=0; i<n; i++)
for (int j=0; j<n; j++)
cost[i][j] = s.nextInt();

System.out.println("Enter the source vertex");


source = s.nextInt();
Dijkstra(source);

System.out.println(" the shortest distance is...");


for(int i=0; i<n; i++)
System.out.println("Cost from "+source+" to "+i+" is " + dist[i]);
}
}

You might also like