Go through every station and check if using it as an intermediate station gives better path
for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( dist [ j ] > dist [ i ] + cost [ i ] [ j ] ) : NEW_LINE INDENT dist [ j ] = dist [ i ] + cost [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return dist [ N - 1 ] NEW_LINE