Recursive Backtracking:
an implicit solution tree is built, but when it becomes apparent that the current path cannot lead to the desired solution, rather than return to the root node, the latest alteration is undone and an alternative is chosen. This means the computational work done in reaching the current point is not wasted. Perhaps a more significant saving is that in some cases this would mean that that search path could be abandoned before completion.
Suduko:
1. TRAVELLING SALESMAN PROBLEM:
1. package hw15;
2.
3. import java.util.ArrayList;
4.
5. public class TravelingSalesman {
6. // The best path found so far
7. private static ArrayList bestPath;
8. // Length of the best path found so far
9. private static double bestLength;
10.
11. public static void main(String[] args) {
12.
13. // Graph graph = new Graph("simple.txt"); // Small test
14. Graph graph = new Graph("northrend.txt"); // Large test
15.
16. // No path found at first
17. bestPath = null;
18. bestLength = Double.MAX_VALUE;
19.
20. // All paths start with vertex 0
21. ArrayList path = new ArrayList();
22. path.add(0);
23.
24. // Use backtracking search to find the best path
25. find_tsp_path(graph, path);
26.
27. System.out.println("Best path length: " + bestLength);
28. System.out.print("Path: ");
29. for (int v : bestPath)
30. System.out.print(graph.getLabel(v) + " ");
31. System.out.println();
32. }
33.
34. // Copies an array into another array
35. public static ArrayList copyArray(ArrayList source) {
36. int size = source.size();