旅行售貨員問題-回溯法

        旅行售貨員問題使用回溯法構建樹後,需要注意判斷最後的葉結點中的點數據是否和其實點有連接,如果沒有則不是解,如果有則需要把權值加上,纔是解。

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;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章