-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdjikstra.java
More file actions
61 lines (50 loc) · 2.38 KB
/
djikstra.java
File metadata and controls
61 lines (50 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.Arrays;
public class djikstra {
public static int findMinDistance(int[] distance, boolean[] visited, int numberOfNodes) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < numberOfNodes; v++) {
if (!visited[v] && distance[v] < min) {
min = distance[v];
minIndex = v;
}
}
return minIndex;
}
public static void dijkstra(int[][] graph, int source, int numberOfNodes) {
// Array to store the shortest distance from the source to each vertex
int[] distance = new int[numberOfNodes];
// To keep track of vertices included in the shortest path tree
boolean[] visited = new boolean[numberOfNodes];
// Initialize distances to infinity and visited[] to false
Arrays.fill(distance, Integer.MAX_VALUE);
Arrays.fill(visited, false);
// Distance to the source is always 0
distance[source] = 0;
// Find shortest path for all vertices
for (int count = 0; count < numberOfNodes - 1; count++) {
// Pick the vertex with the minimum distance value not yet processed
int u = findMinDistance(distance, visited, numberOfNodes);
// Mark the picked vertex as processed
visited[u] = true;
// Update the distance of the adjacent vertices of the picked vertex
for (int v = 0; v < numberOfNodes; v++) {
// Update distance[v] only if:
// - There's an edge from u to v
// - v is not yet visited
// - The new distance through u is smaller than the current distance
if (graph[u][v] != 0 && !visited[v] && distance[u] != Integer.MAX_VALUE && distance[u] + graph[u][v] < distance[v]) {
distance[v] = distance[u] + graph[u][v];
}
}
}
// Print the constructed distance array
printSolution(distance, numberOfNodes);
}
// Function to print the distances from the source to each vertex
public static void printSolution(int[] distance, int numberOfNodes) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < numberOfNodes; i++) {
System.out.println(i + " \t\t " + distance[i]);
}
}
}