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