miku
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import java.util.*;
|
||||
public class dijkstra{
|
||||
static int V;
|
||||
static int minDistance(int[] dist, boolean[] visited){
|
||||
int min = Integer.MAX_VALUE;
|
||||
int minIndex = -1;
|
||||
for(int v=0;v<V;v++){
|
||||
if(!visited[v] && dist[v]<min){
|
||||
min = dist[v];
|
||||
minIndex = v;;
|
||||
}
|
||||
}
|
||||
return minIndex;
|
||||
}
|
||||
|
||||
static void printPath(int vertex, int[] parent){
|
||||
if(vertex==-1) return;
|
||||
printPath(parent[vertex], parent);
|
||||
System.out.print(vertex+" ");
|
||||
}
|
||||
|
||||
static void dijkstra(int[][] graph, int source){
|
||||
int[] dist = new int[V];
|
||||
boolean[] visited = new boolean[V];
|
||||
int[] parent = new int[V];
|
||||
|
||||
Arrays.fill(dist, Integer.MAX_VALUE);
|
||||
for(int i=0;i<V;i++)
|
||||
parent[i] = -1;
|
||||
dist[source] = 0;
|
||||
long start = System.nanoTime();
|
||||
for(int count=0;count<V-1;count++){
|
||||
int u = minDistance(dist, visited);
|
||||
visited[u] = true;
|
||||
for(int v=0;v<V;v++){
|
||||
if(!visited[v] && graph[u][v]!=0 && dist[u]!=Integer.MAX_VALUE && dist[u]+graph[u][v]<dist[v]){
|
||||
dist[v] = dist[u]+graph[u][v];
|
||||
parent[v] = u;
|
||||
}
|
||||
}
|
||||
}
|
||||
long end = System.nanoTime();
|
||||
|
||||
System.out.println("\nSHortest distances from source "+source+":");
|
||||
for(int i =0;i<V;i++){
|
||||
System.out.println("Vetex: "+i);
|
||||
System.out.println("Cost: "+dist[i]);
|
||||
System.out.println("Path: ");
|
||||
printPath(i, parent);
|
||||
System.out.println("\n");
|
||||
}
|
||||
long executionTime = end - start;
|
||||
|
||||
System.out.println("Execution Time: " + executionTime + " nanoseconds");
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("\nENter number of vertices: ");
|
||||
V = sc.nextInt();
|
||||
int[][] graph = new int[V][V];
|
||||
System.out.println("ENter adjacency matrix: ");
|
||||
for(int i=0;i<V;i++){
|
||||
for(int j =0;j<V;j++){
|
||||
graph[i][j] =sc.nextInt();
|
||||
}
|
||||
}
|
||||
int source = 0;
|
||||
dijkstra(graph, source);
|
||||
sc.close();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user