@@ -611,12 +611,11 @@ class Dijkstra extends Grafo {
611
611
const dist = Array ( n ) . fill ( 0xFFFFFFFF ) ;
612
612
const visitado = Array ( n ) . fill ( false ) ;
613
613
const caminho = [ ] ;
614
+ const antecessor = Array ( n ) . fill ( false ) ;
614
615
615
616
function dijkstra ( s , t ) {
616
617
dist [ s ] = 0 ;
617
618
618
- let noAnterior = false ;
619
-
620
619
while ( true ) {
621
620
let no = false ; // vértice com o caminho mais curto.
622
621
for ( let i = 0 ; i < n ; i ++ ) {
@@ -627,36 +626,37 @@ class Dijkstra extends Grafo {
627
626
628
627
if ( no === false ) break ;
629
628
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ó.
637
630
638
631
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 ;
642
635
if ( ( dist [ no ] + peso ) < dist [ i ] ) {
643
636
dist [ i ] = dist [ no ] + peso ;
637
+ antecessor [ i ] = no ;
644
638
}
645
639
}
646
640
}
647
641
648
- if ( no === verticeFinal ) {
649
- break ;
650
- }
642
+ if ( no === verticeFinal ) break ;
651
643
}
652
644
653
645
console . log ( `distancia de ${ s } até ${ t } : ${ dist [ t ] } ` ) ;
654
646
}
655
647
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
+
656
655
//Limpa os estilos.
657
656
this . limparEstiloDoGrafo ( ) ;
658
657
659
658
dijkstra ( verticeInicial , verticeFinal ) ;
659
+ percorrerAntecessores ( verticeFinal ) ;
660
660
661
661
const stepper = new Stepper ( caminho , 3 , this . velocidadeDaAnimacao ) ;
662
662
stepper . executar ( ( m , i , k ) => {
0 commit comments