旅行售货员问题使用回溯法构建树后,需要注意判断最后的叶结点中的点数据是否和其实点有连接,如果没有则不是解,如果有则需要把权值加上,才是解。
package test; import java.util.ArrayList; import java.util.List; /** * Created by saishangmingzhu on 2018/12/12. * 旅行售货员问题 */ public class TravellingSalesmanProblem { //图 private int[][] pointIndex=new int[][]{ {0,30,6,4}, {30,0,5,10}, {6,5,0,20}, {4,10,20,0}}; public static void main(String[] arg){ new TravellingSalesmanProblem().backtracking(); } /** * 回溯法 */ private void backtracking(){ //【1】构建树,深度遍历,计算当前最优值,之后的遍历中作为剪支判断 List<Point> pointList=new ArrayList<>(); pointList.add(new Point(0,"1")); pointList.add(new Point(1,"2")); pointList.add(new Point(2,"3")); pointList.add(new Point(3,"4")); Node root=new Node(); root.point=pointList.get(0); Node minNode=new Node(); minNode.value=Integer.MAX_VALUE; childList(root,pointList,minNode); System.out.println(minNode.value); getParents(minNode); } private void getParents(Node node){ if (node==null){ return; } getParents(node.parentNode); System.out.println(node.point.name); } private void childList(Node node,List<Point> pointList,Node minNode){ Point point=node.point; pointList.remove(point); for (Point childPoint:pointList){ int value=pointIndex[point.index][childPoint.index]; if (value!=0) { Node childNode=new Node(); childNode.parentNode=node; childNode.point=childPoint; childNode.value=value+node.value; node.childNodeList.add(childNode); List<Point> pointList1=new ArrayList<>(); pointList1.addAll(pointList); childList(childNode,pointList1,minNode); } } if (pointList.size()==0&&pointIndex[0][point.index]!=0){ int value=node.value+pointIndex[0][point.index]; node.value=value; if (value<minNode.value){ minNode.value=value; minNode.point=node.point; minNode.parentNode=node.parentNode; } } } class Node{ private Node parentNode; private Point point; private List<Node> childNodeList=new ArrayList<>(); private int value; } class Point{ private int index; private String name; public Point(int index, String name) { this.index = index; this.name = name; } } }