1
- // Algoritimo de Dijkstra
1
+ // Algoritimo de Dijkstra (Dijkstra's Algorithm)
2
2
// Anderson Carneiro da Silva
3
3
// https://github.com/AndersonSheep
4
4
5
- // Baseado no método do GeekforGeeks
6
- // Um programa Java para o algoritmo de caminho mais curto de fonte única de Dijkstra.
7
- // O programa é para representação da matriz de adjacência do grafo
5
+ // Baseado no método do GeekforGeeks
6
+ // Um programa Java para o algoritmo de caminho mais curto de fonte única de Dijkstra.
7
+ // O programa é para representação da matriz de adjacência do grafo
8
+
9
+ /* Based on the GeekforGeeks method
10
+ A Java program for Dijkstra's single-source shortest path algorithm.
11
+ The program is for the representation of the graph's adjacency matrix */
12
+
8
13
import java .io .*;
9
14
import java .util .*;
10
15
11
16
class ShortestPath {
12
17
// Uma função de utilidade para encontrar o vértice com valor mínimo de distância,
13
18
// do conjunto de vértices ainda não incluídos na árvore do caminho mais curto
19
+
20
+ /* A utility function to find the vertex with the minimum distance value,
21
+ from the set of vertices not yet included in the shortest path tree */
14
22
static final int V = 9 ;
15
23
16
24
int minDistance (int dist [], Boolean sptSet []) {
17
25
// Iniciando um valor minimo
26
+ // Initializing a minimum value
18
27
int min = Integer .MAX_VALUE , min_index = -1 ;
19
28
20
29
for (int v = 0 ; v < V ; v ++) {
@@ -28,6 +37,7 @@ int minDistance(int dist[], Boolean sptSet[]) {
28
37
}
29
38
30
39
// Uma função de utilidade para imprimir a matriz de distância construída
40
+ // A utility function to print the constructed distance matrix
31
41
void printSolution (int dist []) {
32
42
System .out .println ("Vertex \t \t Distance from Source" );
33
43
for (int i = 0 ; i < V ; i ++) {
@@ -37,38 +47,57 @@ void printSolution(int dist[]) {
37
47
38
48
// Função que implementa o caminho mais curto da fonte única de Dijkstra
39
49
// algoritmo para um grafo representado usando matriz de adjacência
50
+
51
+ /* Function that implements Dijkstra's single-source shortest path algorithm
52
+ for a graph represented using an adjacency matrix */
40
53
void dijkstra (int graph [][], int src ) {
41
54
// A matriz de saída. dist [i] irá manter a menor distância de src a i
55
+ // The output array. dist[i] will hold the shortest distance from src to i
42
56
int dist [] = new int [V ];
43
57
44
58
// sptSet [i] será verdadeiro se o vértice i for incluído no mais curto
45
59
// árvore do caminho ou distância mais curta de src para i é finalizada
60
+
61
+ /* sptSet[i] will be true if vertex i is included in the shortest
62
+ path tree or the shortest distance from src to i is finalized */
46
63
Boolean sptSet [] = new Boolean [V ];
47
64
48
65
// Inicializa todas as distâncias como INFINITE e stpSet [] como falso
66
+ // Initialize all distances as INFINITE and sptSet[] as false
49
67
for (int i = 0 ; i < V ; i ++) {
50
68
dist [i ] = Integer .MAX_VALUE ;
51
69
sptSet [i ] = false ;
52
70
}
53
71
54
72
// A distância do vértice de origem é sempre 0
73
+ // The distance of the source vertex is always 0
55
74
dist [src ] = 0 ;
56
75
57
76
// Encontre o caminho mais curto para todos os vértices
77
+ // Find the shortest path for all vertices
58
78
for (int count = 0 ; count < V - 1 ; count ++) {
59
79
// Escolha o vértice de distância mínima do conjunto de vértices
60
80
// ainda não processado. vc é sempre igual a src na primeira iteração.
81
+
82
+ /* Pick the vertex with the minimum distance from the set of vertices
83
+ not yet processed. u is always equal to src in the first iteration. */
61
84
int u = minDistance (dist , sptSet );
62
85
63
86
// Marque o vértice escolhido como processado
87
+ // Mark the chosen vertex as processed
64
88
sptSet [u ] = true ;
65
89
66
90
// Atualize o valor dist dos vértices adjacentes do vértice escolhido.
91
+ // Update the value dist for the adjacent vertices of the chosen vertex.
67
92
for (int v = 0 ; v < V ; v ++)
68
93
69
94
// Atualize dist [v] apenas se não estiver em sptSet, há um
70
95
// borda de u a v, e peso total do caminho de src a
71
96
// v a u é menor que o valor atual de dist [v]
97
+
98
+ /* Update dist[v] only if it's not in sptSet, there is an edge from u to v,
99
+ and the total weight of the path from src to v through u is less than the
100
+ current value of dist[v] */
72
101
if (!sptSet [v ]
73
102
&& graph [u ][v ] != 0
74
103
&& dist [u ] != Integer .MAX_VALUE
@@ -78,11 +107,13 @@ void dijkstra(int graph[][], int src) {
78
107
}
79
108
80
109
// Imprime a matriz de distância construída
110
+ // Print the constructed distance matrix
81
111
printSolution (dist );
82
112
}
83
113
84
114
public static void main (String [] args ) {
85
115
// Vamos criar o gráfico de exemplo discutido acima
116
+ //Let's create the example graph discussed above
86
117
int graph [][] =
87
118
new int [][] {
88
119
{0 , 4 , 0 , 0 , 0 , 0 , 0 , 8 , 0 },
0 commit comments