I am trying to implement the Divide and Conquer Algorithm to solve the Traveling Salesman problem. I divided the problem into smaller parts, but I have no idea what to do next.
Here is my code:
struct coordinate
{
float x;
float y;
};
vector<coordinate> coordinates; //Please assume it is filled with random coordinates
void DivideAndConquer(int divide)
{
vector<vector<coordinate>> routes;
vector<coordinate> empty;
int check = 0;
for (int i = 0; i < coordinates.size(); i++)
{
if (i == divide * check)
{
check++;
routes.push_back(empty);
}
routes[check - 1].push_back(coordinates[i]);
}
//What now?
}
I also implemented methods to calculate distance:
float Distance(coordinate first, coordinate second)
{
return sqrt(pow(second.x - first.x, 2) + pow(second.y - first.y, 2) * 1.0);
}
float RouteDistance(vector<coordinate> route, bool returnBack)
{
float totalDistance = 0;
for (int i = 1; i < route.size(); i++)
{
totalDistance += Distance(route[i-1], route[i]);
}
if (returnBack) totalDistance += Distance(route[0], route[route.size() - 1]);
return totalDistance;
}
I wrote Brute Force algorithm as well, which I believe can be used in divide and conquer. It simply returns to most optimal route of given coordinate vector.
vector<coordinate> BruteForce(vector<coordinate> route)
{
vector<int> turn;
for (int i = 0; i < route.size(); i++) turn.push_back(i);
int currentBestDistance = RouteDistance(route, true);
vector<coordinate> currentBestRoute = route;
do
{
vector<coordinate> newRoute;
int newRouteDistance;
for (int e : turn)
{
newRoute.push_back(route[e]);
}
newRouteDistance = RouteDistance(newRoute, false);
if (newRouteDistance < currentBestDistance)
{
currentBestRoute = newRoute;
currentBestDistance = newRouteDistance;
}
} while (next_permutation(turn.begin(), turn.end()));
return currentBestRoute;
}
In DivideAndConquer it currently divides the coordinates vector into sub vectors size of the "divide" parameter we call the function with.
For example, let's assume this is our coordinates:
10 20
23 54
98 123
55 72
16 82
And we call "DivideAndConquer(2)"
result:
10 20
23 54
98 123
55 72
16 82