|
10 | 10 | * @author asadp
|
11 | 11 | */
|
12 | 12 | public class Dijkstra {
|
13 |
| - |
| 13 | + public static void dijkstra(int[][] graph, int source) { |
| 14 | + int count = graph.length; |
| 15 | + boolean[] visitedVertex = new boolean[count]; |
| 16 | + int[] distance = new int[count]; |
| 17 | + for (int i = 0; i < count; i++) { |
| 18 | + visitedVertex[i] = false; |
| 19 | + distance[i] = Integer.MAX_VALUE; |
| 20 | + } |
| 21 | + |
| 22 | + // Distance of self loop is zero |
| 23 | + distance[source] = 0; |
| 24 | + for (int i = 0; i < count; i++) { |
| 25 | + |
| 26 | + // Update the distance between neighbouring vertex and source vertex |
| 27 | + int u = findMinDistance(distance, visitedVertex); |
| 28 | + visitedVertex[u] = true; |
| 29 | + |
| 30 | + // Update all the neighbouring vertex distances |
| 31 | + for (int v = 0; v < count; v++) { |
| 32 | + if (!visitedVertex[v] && graph[u][v] != 0 && (distance[u] + graph[u][v] < distance[v])) { |
| 33 | + distance[v] = distance[u] + graph[u][v]; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + for (int i = 0; i < distance.length; i++) { |
| 38 | + System.out.println(String.format("Distance from %s to %s is %s", source, i, distance[i])); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Finding the minimum distance |
| 43 | + private static int findMinDistance(int[] distance, boolean[] visitedVertex) { |
| 44 | + int minDistance = Integer.MAX_VALUE; |
| 45 | + int minDistanceVertex = -1; |
| 46 | + for (int i = 0; i < distance.length; i++) { |
| 47 | + if (!visitedVertex[i] && distance[i] < minDistance) { |
| 48 | + minDistance = distance[i]; |
| 49 | + minDistanceVertex = i; |
| 50 | + } |
| 51 | + } |
| 52 | + return minDistanceVertex; |
| 53 | + } |
| 54 | + |
| 55 | + public static void main(String[] args) { |
| 56 | + int graph[][] = new int[][] { { 0, 0, 1, 2, 0, 0, 0 }, { 0, 0, 2, 0, 0, 3, 0 }, { 1, 2, 0, 1, 3, 0, 0 }, |
| 57 | + { 2, 0, 1, 0, 0, 0, 1 }, { 0, 0, 3, 0, 0, 2, 0 }, { 0, 3, 0, 0, 2, 0, 1 }, { 0, 0, 0, 1, 0, 1, 0 } }; |
| 58 | + Dijkstra T = new Dijkstra(); |
| 59 | + T.dijkstra(graph, 0); |
| 60 | + } |
14 | 61 | }
|
0 commit comments