-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathDijkstra.java
More file actions
85 lines (66 loc) · 2.62 KB
/
Dijkstra.java
File metadata and controls
85 lines (66 loc) · 2.62 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class Dijkstra {
static class Graph{
int vertices;
int matrix[][];
public Graph(int vertex) {
this.vertices = vertex;
matrix = new int[vertex][vertex];
}
public void addEdge(int source, int destination, int weight)
matrix[source][destination]=weight;
matrix[destination][source] = weight;
int getMinimumVertex(boolean [] mst, int [] key){
int minKey = Integer.MAX_VALUE;
int vertex = -1;
for (int i = 0; i <vertices ; i++) {
if(mst[i]==false && minKey>key[i]){
minKey = key[i];
vertex = i;
}
}
return vertex;
}
public void dijkstra_GetMinDistances(int sourceVertex){
boolean[] spt = new boolean[vertices];
int [] distance = new int[vertices];
int INFINITY = Integer.MAX_VALUE;
for (int i = 0; i <vertices ; i++) {
distance[i] = INFINITY;
}
distance[sourceVertex] = 0;
for (int i = 0; i <vertices ; i++) {
int vertex_U = getMinimumVertex(spt, distance);
spt[vertex_U] = true;
for (int vertex_V = 0; vertex_V <vertices ; vertex_V++) {
if(matrix[vertex_U][vertex_V]>0){
if(spt[vertex_V]==false && matrix[vertex_U][vertex_V]!=INFINITY){
int newKey = matrix[vertex_U][vertex_V] + distance[vertex_U];
if(newKey<distance[vertex_V])
distance[vertex_V] = newKey;
}
}
}
printDijkstra(sourceVertex, distance);
}
public void printDijkstra(int sourceVertex, int [] key){
System.out.println("Dijkstra Algorithm: (Adjacency Matrix)");
for (int i = 0; i <vertices ; i++) {
System.out.println("Source Vertex: " + sourceVertex + " to vertex " + + i +
" distance: " + key[i]);
}
}
}
public static void main(String[] args) {
int vertices = 6;
Graph graph = new Graph(vertices);
int sourceVertex = 0;
graph.addEdge(0, 1, 4);
graph.addEdge(0, 2, 3);
graph.addEdge(1, 2, 1);
graph.addEdge(1, 3, 2);
graph.addEdge(2, 3, 4);
graph.addEdge(3, 4, 2);
graph.addEdge(4, 5, 6);
graph.dijkstra_GetMinDistances(sourceVertex);
}
}