TSP_nearest_Rcpp | R Documentation |
This function implements the **Nearest Insertion** heuristic approach for solving the Traveling Salesman Problem (TSP) in C++ and is exported to R using Rcpp. The algorithm builds the tour by inserting cities into the existing tour by selecting the nearest city to any city already in the tour.
The algorithm starts from a specified city and iteratively inserts cities one by one, choosing the nearest city to any city already in the tour. In "all" mode, the best tour is selected by testing all possible starting cities and computing the total distance for each tour.
TSP_nearest_Rcpp(data, type = "one")
data |
A numeric matrix or data frame where each row represents a city and each column represents the coordinates of that city (e.g., x and y coordinates in 2D space). |
type |
A character string specifying how the starting city is chosen. Options include:
|
The algorithm is a heuristic approach and does not guarantee the global optimal solution, but aims to find a good solution in a reasonable amount of time.
Time Complexity: O(n³), where 'n' is the number of cities. The algorithm computes the best insertion for each city and tries every possible insertion position.
Space Complexity: O(n²) due to the storage of the distance matrix.
The result is a tour with the shortest found distance, based on the starting point(s) and insertion method.
A numeric vector representing the order of cities in the shortest found tour. The vector is assigned the class "TSP".
n <- 40
villes <- matrix(runif(2*n), n, 2)
TSP_nearest_Rcpp(villes, type = "one")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.