Skip to content

Commit 1d862a0

Browse files
committed
Corrigir bug ao gerar o caminho do algoritmo Dijkstra
1 parent f7194fd commit 1d862a0

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

js/grafo.js

+15-15
Original file line numberDiff line numberDiff line change
@@ -611,12 +611,11 @@ class Dijkstra extends Grafo {
611611
const dist = Array(n).fill(0xFFFFFFFF);
612612
const visitado = Array(n).fill(false);
613613
const caminho = [];
614+
const antecessor = Array(n).fill(false);
614615

615616
function dijkstra(s, t) {
616617
dist[s] = 0;
617618

618-
let noAnterior = false;
619-
620619
while (true) {
621620
let no = false; // vértice com o caminho mais curto.
622621
for (let i = 0; i < n; i++) {
@@ -627,36 +626,37 @@ class Dijkstra extends Grafo {
627626

628627
if (no === false) break;
629628

630-
if (noAnterior !== false) {
631-
caminho.push(matriz[noAnterior][no]);
632-
}
633-
634-
noAnterior = no;
635-
636-
visitado[no] = true;
629+
visitado[no] = true; // Elimina o nó.
637630

638631
for (let i = 0; i < n; i++) {
639-
const aresta = matriz[no][i];
640-
if (aresta) {
641-
const peso = aresta.edge.data("peso");
632+
const m = matriz[no][i];
633+
if (m) {
634+
const peso = m.edge.data("peso") || 0;
642635
if ((dist[no] + peso) < dist[i]) {
643636
dist[i] = dist[no] + peso;
637+
antecessor[i] = no;
644638
}
645639
}
646640
}
647641

648-
if (no === verticeFinal) {
649-
break;
650-
}
642+
if (no === verticeFinal) break;
651643
}
652644

653645
console.log(`distancia de ${s} até ${t}: ${dist[t]}`);
654646
}
655647

648+
function percorrerAntecessores(v) {
649+
if (antecessor[v] === false) return;
650+
percorrerAntecessores(antecessor[v]);
651+
const m = matriz[antecessor[v]][v];
652+
caminho.push(m);
653+
}
654+
656655
//Limpa os estilos.
657656
this.limparEstiloDoGrafo();
658657

659658
dijkstra(verticeInicial, verticeFinal);
659+
percorrerAntecessores(verticeFinal);
660660

661661
const stepper = new Stepper(caminho, 3, this.velocidadeDaAnimacao);
662662
stepper.executar((m, i, k) => {

0 commit comments

Comments
 (0)