lab1/src/stsm.cpp
/* using recursive DFS to find the best solution. */
using recursive DFS to find the best solution.
using recursive DFS to find the best solution .
void dfs(
    int** matrix, 
    const int& num_cities, 
    int current_layer, 
    int previous_city, 
    int current_city, 
    int current_distance, 
    int visited_cities, 
    int& min_distance, 
    int* current_route, 
    int* best_route 
) 
{
    current_route[current_layer] = current_city;
    current_distance += matrix[previous_city][current_city];
    if (current_distance >= min_distance) {
        return;
    }
    if (current_layer == num_cities - 1) {
        min_distance = current_distance;
        for (int i = 0; i < num_cities; i++) {
            best_route[i] = current_route[i];
        }
    } else {
        visited_cities |= (1 << current_city);
        for (int i = 1; i < num_cities; i++) {
            if (!(visited_cities & (1 << i))) {
                dfs(
                    matrix,
                    num_cities,
                    current_layer + 1,
                    current_city,
                    i,
                    current_distance,
                    visited_cities,
                    min_distance,
                    current_route,
                    best_route
                );
            }
        }
    }
}
void dfs ( int * * matrix , const int & num_cities , int current_layer , int previous_city , int current_city , int current_distance , int visited_cities , int & min_distance , int * current_route , int * best_route ) { current_route [ current_layer ] = current_city ; current_distance += matrix [ previous_city ] [ current_city ] ; if ( current_distance >= min_distance ) { return ; } if ( current_layer == num_cities - 1 ) { min_distance = current_distance ; for ( int i = 0 ; i < num_cities ; i ++ ) { best_route [ i ] = current_route [ i ] ; } } else { visited_cities |= ( 1 << current_city ) ; for ( int i = 1 ; i < num_cities ; i ++ ) { if ( ! ( visited_cities & ( 1 << i ) ) ) { dfs ( matrix , num_cities , current_layer + 1 , current_city , i , current_distance , visited_cities , min_distance , current_route , best_route ) ; } } } }
using recursive DFS to find the best solution.
using recursive DFS to find the best solution .
// the distance matrix // number of cities // how many cities, including the current one, have been visited // the id of previous city visited // the id of current city visited // the current total distance so far // indicator of visited cities, using bit manipulation // minimum distance so far // array of current path // array of the best path found so far