Advertisement
Guest User

Untitled

a guest
Nov 29th, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. private static int[][] adjacencyMatrix;
  2. private static int[] visitedCities;
  3. private static int[] bestPath;
  4.  
  5. private static int numberOfCities;
  6. private static int bestDistance;
  7.  
  8. /* Depth-first Search */
  9. /*
  10. * 10 cities:
  11. * - without cut : 133
  12. * - with cut : 32
  13. */
  14. public static int[] dfs(int[][] adjacencyMatrix){
  15.  
  16. TSP.adjacencyMatrix = adjacencyMatrix;
  17.  
  18. numberOfCities = adjacencyMatrix.length;
  19.  
  20. visitedCities = new int[numberOfCities];
  21.  
  22. bestDistance = Integer.MAX_VALUE;
  23.  
  24. // +1 because in the end we have to put 0 again
  25. bestPath = new int[numberOfCities + 1];
  26.  
  27. dfsSearch(0,0,0);
  28.  
  29. return bestPath;
  30. }
  31.  
  32. private static void dfsSearch(int cityIndex, int amountOfCitiesPassed, int passedDistance) {
  33.  
  34. // Add current city to visited list
  35. visitedCities[amountOfCitiesPassed] = cityIndex;
  36.  
  37. // If amount of cities passed is number of all cities - 1
  38. // then it means that all cities are visited and we have to go back to start
  39. if (amountOfCitiesPassed == (numberOfCities - 1)) {
  40.  
  41. int wholeTripLength = passedDistance + adjacencyMatrix[cityIndex][0];
  42.  
  43. if (wholeTripLength < bestDistance) {
  44. bestDistance = wholeTripLength;
  45.  
  46. // Create best path from visited cities
  47. System.arraycopy(visitedCities, 0, bestPath, 0, visitedCities.length);
  48.  
  49. // Add going back to 0 into path
  50. bestPath[numberOfCities] = 0;
  51.  
  52. }
  53.  
  54. } else {
  55. // Loop over rows
  56. for(int next = 0; next < numberOfCities; next++) {
  57.  
  58. // If current passed length + length to next city is smaller than
  59. // current best distance.
  60. if (passedDistance + adjacencyMatrix[cityIndex][next] < bestDistance) {
  61.  
  62. // Check if 'next' is already visited
  63. boolean isPassed = false;
  64. for (int i = 0; i < amountOfCitiesPassed + 1; i++){
  65. if (visitedCities[i] == next) {
  66. isPassed = true;
  67. break;
  68. }
  69. }
  70.  
  71. if (!isPassed) {
  72. dfsSearch(next,
  73. amountOfCitiesPassed + 1,
  74. passedDistance + adjacencyMatrix[cityIndex][next]);
  75. }
  76. }
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement