I\'m working on a project for a math class at school, and I chose to do mine on the Traveling Salesman Problem, something I\'ve always wanted to investigate more. However, I\'m
You should remove cities from the route after the recursive call returns. You do this:
Route newRoute = r;
newRoute.addToRoute(citiesNotInRoute.get(i));
BruteForceFindBestRoute(newRoute);
but never a newRoute.removeFromRoute
or similar.
Note that you are writing Java, and in Java, an assignment of an object is done by reference. Which means that r
and newRoute
are the same object. newRoute
is not an independent copy of r
as you might expect. So any modification to newRoute
will change r
as well. You might want to explicitely copy your route there. The Java term for this is clone. Make sure your clone is deep enough, i.e. you clone all relevant data structures, instead of sharing them between the original and its clone.
Note: There are many places where you might make your code more efficient, but as brute force is far from efficient in any case, and you're only talking about few cities, perhaps you don't have to care. If you want to investigate alternatives, though, consider maintaining a single linked list of all unvisited cities. Each call would loop over that list, remove an element, recurse and put the element back. No need to build this list from scratch in each invocation. The idea of dancing links could be neatly applied to this task, as an alternative to premade linked list implementations.
EDIT:
The following variation of your code works for me:
import java.util.*;
class SO11703827 {
private static ArrayList bestRoute;
public static void bruteForceFindBestRoute
(ArrayList r,
ArrayList citiesNotInRoute)
{
if(!citiesNotInRoute.isEmpty())
{
for(int i = 0; i newRoute =
(ArrayList) r.clone();
newRoute.add(justRemoved);
bruteForceFindBestRoute(newRoute, citiesNotInRoute);
citiesNotInRoute.add(justRemoved);
}
}
else //if(citiesNotInRoute.isEmpty())
{
if(isBestRoute(r))
bestRoute = r;
}
}
private static boolean isBestRoute(ArrayList r) {
System.out.println(r.toString());
return false;
}
public static void main(String[] args) {
ArrayList lst = new ArrayList();
for (int i = 0; i < 6; ++i)
lst.add(i);
ArrayList route = new ArrayList();
bruteForceFindBestRoute(route, lst);
}
}