package javaCodes;
import java.util.ArrayList;
import java.util.Scanner;
class dijkstra
{
private int vertices = 9;
void shortest_path(int g[][], int source)
{
int dis[] = new int[vertices];
boolean sptset[] = new boolean[vertices];
ArrayList<ArrayList<Integer>> path = new ArrayList<ArrayList<Integer>> (vertices);
for(int i=0; i < vertices; i++)
{
dis[i] = Integer.MAX_VALUE;
sptset[i] = false;
path.add(new ArrayList<Integer> ());
}
dis[source] = 0;
for(int v=0; v<vertices; v++)
{
int u = mindistance(dis, sptset);
sptset[u] = true;
for(int i=0; i<vertices; i++)
{
if(!sptset[i] && dis[u]!= Integer.MAX_VALUE && g[u][i]!=0 && dis[u] + g[u][i] < dis[i])
{
if(dis[i] == Integer.MAX_VALUE)
{
dis[i] = dis[u] + g[u][i];
for(int k=0; k < path.get(u).size(); k++)
{
path.get(i).add(path.get(u).get(k));
}
path.get(i).add(u);
}
else
{
dis[i] = dis[u] + g[u][i];
path.get(i).clear();
for(int k=0; k < path.get(u).size(); k++)
{
path.get(i).add(path.get(u).get(k));
}
path.get(i).add(u);
}
}
}
}
display(dis, path);
}
int mindistance(int[] dis, boolean[] sptset) {
int min = Integer.MAX_VALUE, min_index = -1;
for(int i=0; i<vertices; i++)
{
if(!sptset[i] && dis[i] < min)
{
min = dis[i];
min_index = i;
}
}
return min_index;
}
void display(int[] dis, ArrayList<ArrayList<Integer>> path) {
System.out.println("Distance of every node from source is : ");
for(int i=0; i < vertices; i++)
{
System.out.println("Node : "+ i +" "+"Distance : "+dis[i]+" ");
System.out.print("Shortest distance path is : ");
for(int j=0; j<path.get(i).size(); j++)
{
System.out.print(path.get(i).get(j)+" ");
}
System.out.println("\n");
}
}
}
public class Dijkstra_algorithm {
public static void main(String args[])
{
int arr[][] = new int[9][9];
for(int i=0; i<=8; i++)
{
for(int j=0; j<=8; j++)
{
arr[i][j] = 0;
}
}
int edges;
Scanner sc = new Scanner(System.in);
System.out.print("Enter no of edges : ");
edges = sc.nextInt();
for(int i=0; i<edges; i++)
{
System.out.print("Now Enter left, right vertex and edge weight: ");
int temp1, temp2, temp3;
temp1 = sc.nextInt();
temp2 = sc.nextInt();
temp3 = sc.nextInt();
arr[temp1][temp2] = temp3;
arr[temp2][temp1] = temp3;
}
dijkstra obj = new dijkstra();
obj.shortest_path(arr, 0);
}
}
No comments:
Post a Comment