Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Created August 6, 2019 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/d452d9da2f92bf55bd88aa2558b0f488 to your computer and use it in GitHub Desktop.
Save RitamChakraborty/d452d9da2f92bf55bd88aa2558b0f488 to your computer and use it in GitHub Desktop.
Travelling Salesman Problem implemented in java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TravellingSalesmanProblem {
private static final int startingIndex;
private static final int[][] arr = {{0, 10, 15, 20}, {5, 0, 9, 10}, {6, 13, 0, 12}, {8, 8, 9, 0}};
static {
startingIndex = 0;
}
private static int getMinimumCost(int i, List<Integer> list) {
if (list.isEmpty()) {
return arr[i][startingIndex];
} else {
List<Integer> costs = new ArrayList<>();
for (int j: list) {
List<Integer> remaining = new ArrayList<>();
for (int k: list) {
if (j != k) {
remaining.add(k);
}
}
costs.add(arr[i][j] + getMinimumCost(j, remaining));
}
return Collections.min(costs);
}
}
public static void main(String[] args) {
System.out.println(getMinimumCost(0, IntStream.of(1, 2, 3).boxed().collect(Collectors.toList())));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment