-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraAlgorithm
More file actions
58 lines (48 loc) · 2.13 KB
/
DijkstraAlgorithm
File metadata and controls
58 lines (48 loc) · 2.13 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
public class DijkstraAlgorithm {
static final int totalVertex = 9;
int minimumDistance(int distance[], Boolean included[]) {
int m = Integer.MAX_VALUE, m_index = -1;
for (int i = 0; i < totalVertex; i++) {
if (included[i] == false && distance[i] < m) {
m = distance[i];
m_index = i;
}
}
return m_index;
}
void printSolution(int distance[], int n) {
System.out.println("The shortest distance from source node to all other nodes are:");
for (int j = 0; j < n; j++) {
System.out.println("The shortest distance to" + " " + j + " " + "is:" + distance[j]);
}
}
void dijkstra(int graph[][], int s) {
int distance[] = new int[totalVertex];
Boolean included[] = new Boolean[totalVertex];
for (int j = 0; j < totalVertex; j++) {
distance[j] = Integer.MAX_VALUE;
included[j] = false;
}
distance[s] = 0;
for (int cnt = 0; cnt < totalVertex - 1; cnt++) {
int ux = minimumDistance(distance, included);
included[ux] = true;
for (int vx = 0; vx < totalVertex; vx++) {
if (!included[vx] && graph[ux][vx] != -1 && distance[ux] != Integer.MAX_VALUE
&& distance[ux] + graph[ux][vx] < distance[vx]) {
distance[vx] = distance[ux] + graph[ux][vx];
}
}
}
printSolution(distance, totalVertex);
}
public static void main(String[] args) {
int grph[][] = new int[][] { { -1, 3, -1, -1, -1, -1, -1, 7, -1 }, { 3, -1, 7, -1, -1, -1, -1, 10, 4 },
{ -1, 7, -1, 6, -1, 2, -1, -1, 1 }, { -1, -1, 6, -1, 8, 13, -1, -1, 3 },
{ -1, -1, -1, 8, -1, 9, -1, -1, -1 }, { -1, -1, 2, 13, 9, -1, 4, -1, 5 },
{ -1, -1, -1, -1, -1, 4, -1, 2, 5 }, { 7, 10, -1, -1, -1, -1, 2, -1, 6 },
{ -1, 4, 1, 3, -1, 5, 5, 6, -1 } };
DijkstraAlgorithm obj = new DijkstraAlgorithm();
obj.dijkstra(grph, 0);
}
}