Bellman Ford (1)
Bellman Ford (1)
void b e l l m a n f o r d ( i n t s ) {
memset ( d i s t , 0 x3f , s i z e o f ( d i s t ) ) ;
d i s t [ s ] = 0;
f o r ( i n t i = 0 ; i < V − 1 ; ++ i )
f o r ( i n t j = 0 ; j < V; ++ j )
f o r ( i n t k = 0 ; k < g r a p h [ j ] . s i z e ( ) ; ++k )
d i s t [ g r a p h [ j ] [ k ] ] = min ( d i s t [ g r a p h [ j ] [ k ] ] , d i s t [ j ] + c o s t [ j ] [ k ] ) ;
}
The Bellman Ford algorithm iterate through each edge V times, and its time complexity is O(V E).
Note that after the k th iteration in the algorithm, we may have found some shortest paths with more
than k edges. However, we are only guaranteed to find shortest paths with less than or equal to k
edges.