1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| public class test {
private static final Queue<Node> queue = new PriorityQueue<>((Comparator.comparingInt(o -> o.distance)));
private static final int[][] matrix = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} };
public static void main(String[] args) { System.out.println(TSP()); }
private static int TSP() { List<Integer> list = new LinkedList<>(); for (int i = 1; i < matrix.length; i++) { list.add(i); } Node node = new Node(list, false, 0, 0); queue.offer(node);
while (!queue.isEmpty()) { node = queue.poll(); if (node.solution) { return node.distance; }
list = node.list; if (list.size() == 0) { node.distance = node.distance + matrix[node.begin][0]; node.solution = true; queue.offer(node); continue; }
int temp = node.distance; if (queue.stream().anyMatch(node1 -> node1.distance <= temp)) { continue; } for (int end : list) { List<Integer> list1 = clone(list, end); int distance = node.distance + matrix[node.begin][end]; Node node1 = new Node(list1, false, end, distance); queue.offer(node1); } } return -1; }
private static class Node { List<Integer> list; boolean solution; int begin; int distance;
public Node(List<Integer> list, boolean solution, int begin, int distance) { this.list = list; this.solution = solution; this.begin = begin; this.distance = distance; } }
private static List<Integer> clone(List<Integer> list, int current) { List<Integer> list1 = new LinkedList<>(); for (Integer temp : list) { if (temp != current) { list1.add(temp); } } return list1; }
}
|