Skip to content

Commit b4ecca3

Browse files
committed
S48
1 parent 2f2b374 commit b4ecca3

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@
1717
/bT/target/
1818
/dFS/target/
1919
/bFS/target/
20+
/dijkstra/target/

dijkstra/src/main/java/com/mycompany/dijkstra/Dijkstra.java

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,52 @@
1010
* @author asadp
1111
*/
1212
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+
}
1461
}

0 commit comments

Comments
 (0)