Dijkstra Seeking the Shortest Path II
Original title link
①. Title
②. Thinking
Dijkstra algorithm uses breadth-first search to solve the single-source shortest path problem of weighted directed graphs or undirected graphs, and the algorithm finally obtains a shortest path tree. This algorithm is often used in routing algorithms or as a sub-module of other graph algorithms.
Dense graphs are stored using adjacency matrix
稀疏图使用邻接表存储
③. Learning points
堆优化Dijkstra
④. Code implementation
import java. io. BufferedReader;
import java. io. IOException;
import java. io. InputStreamReader;
import java. util. Arrays;
import java. util. PriorityQueue;
public class Main {
static int n= 0 , m= 0 , N= 1000010 ;
static PriorityQueue< int [ ] > q= new PriorityQueue < > ( ( a, b) - > {
return a[ 1 ] - b[ 1 ] ; } ) ;
static int [ ] dist= new int [ N] ;
static boolean [ ] f= new boolean [ N] ;
static int [ ] h= new int [ N] , e= new int [ N] , ne= new int [ N] , w= new int [ N] ;
static int idx= 1 ;
public static void main ( String[ ] args) throws IOException {
BufferedReader br = new BufferedReader ( new InputStreamReader ( System. in) ) ;
String[ ] s = br. readLine ( ) . split ( " " ) ;
n= Integer. parseInt ( s[ 0 ] ) ;
m= Integer. parseInt ( s[ 1 ] ) ;
Arrays. fill ( h, - 1 ) ;
for ( int i= 1 ; i<= m; i++ ) {
String[ ] s2 = br. readLine ( ) . split ( " " ) ;
int a= Integer. parseInt ( s2[ 0 ] ) ;
int b= Integer. parseInt ( s2[ 1 ] ) ;
int c= Integer. parseInt ( s2[ 2 ] ) ;
add ( a, b, c) ;
}
System. out. println ( dijkstra ( ) ) ;
}
static void add ( int a, int b, int c) {
e[ idx] = b;
w[ idx] = c;
ne[ idx] = h[ a] ;
h[ a] = idx++ ;
}
static int dijkstra ( ) {
Arrays. fill ( dist, 0x3f3f3f3f ) ;
dist[ 1 ] = 0 ;
q. offer ( new int [ ] {
1 , 0 } ) ;
while ( q. size ( ) != 0 ) {
int [ ] a= q. poll ( ) ;
int t= a[ 0 ] , distance= a[ 1 ] ;
if ( f[ t] ) {
continue ;
}
f[ t] = true ;
for ( int i= h[ t] ; i!= - 1 ; i= ne[ i] ) {
int j= e[ i] ;
if ( dist[ j] > distance+ w[ i] ) {
dist[ j] = distance+ w[ i] ;
q. offer ( new int [ ] {
j, dist[ j] } ) ;
}
}
}
if ( dist[ n] != 0x3f3f3f3f ) return dist[ n] ;
return - 1 ;
}
}