-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDijskstra.java
More file actions
57 lines (48 loc) · 1.82 KB
/
Copy pathDijskstra.java
File metadata and controls
57 lines (48 loc) · 1.82 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
public class Dijskstra {
public static void main(String[] args) {
int[][] graph = {{0,6,0,1,0},
{6,0,5,2,2},
{0,5,0,0,5},
{1,2,0,0,1},
{0,2,5,1,0}};
int start = 0;
int finish = 2;
dijskstra(graph, start, finish);
}
private static void dijskstra(int[][] graph, int start, int finish) {
int v = graph.length;
boolean visited[] = new boolean[v];
int distance[] = new int[v];
distance[start] = 0;
for (int i = 1; i < v; i++) {
distance[i] = Integer.MAX_VALUE;
}
for(int i = 0; i < v-1; i++){
//tìm đỉnh kề có khoảng cách nhỏ nhất
int minVertex = findMinVertex(distance, visited);
visited[minVertex] = true;
//tìm đỉnh kề với đỉnh vừa tìm
for (int j = 0; j < v; j++) {
if(graph[minVertex][j] != 0 && !visited[j] && distance[minVertex] != Integer.MAX_VALUE){
int newDistance = distance[minVertex] + graph[minVertex][j];
if(newDistance < distance[j]){
distance[j] = newDistance;
}
}
}
}
System.out.println(start + "->" +finish+ " = " + distance[finish]);
// for (int i = 0; i < v; i++) {
// System.out.println(i + " " + distance[i]);
// }
}
private static int findMinVertex(int[] distance, boolean[] visited) {
int minVertex = -1;
for (int i = 0; i < distance.length; i++) {
if(!visited[i] && (minVertex == -1 || distance[i] < distance[minVertex])){
minVertex = i;
}
}
return minVertex;
}
}