旅行售货员问题 java_旅行售货员问题-分支界限法

本文介绍了如何使用Java实现旅行售货员问题的分支界限法求解。通过创建节点类和点类,构建优先队列式结构,逐步搜索找到最优解。在代码中,首先初始化图,然后利用分支界限法进行求解,输出最短路径的总距离。
摘要由CSDN通过智能技术生成

旅行售货员问题分支界限法

package test;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

/**

* Created by saishangmingzhu on 2018/12/13.

* 旅行售货员问题

*/

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().branchAndBoundMethod();

}

/**

* 分支界限法-优先队列式

* 优先队列式求解时,到达第一个没有子结点的活结点时,即为最优解

*/

public void branchAndBoundMethod() {

List 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);

root.childPointList.addAll(pointList);

root.childPointList.remove(root.point);

Node minNode=new Node();

minNode.value=Integer.MAX_VALUE;

List currentLiveNodeList=new ArrayList<>();

currentLiveNodeList.add(root);

while (currentLiveNodeList.size()>0) {

Node liveNode = currentLiveNodeList.get(0);

List childPointList = liveNode.childPointList;

for (Point childPoint : childPointList) {

int value=pointIndex[childPoint.index][liveNode.point.index];

if (value!=0) {

Node childNode = new Node();

childNode.parentNode=liveNode;

childNode.point = childPoint;

childNode.childPointList.addAll(childPointList);

childNode.childPointList.remove(childPoint);

childNode.value = liveNode.value + value;

if (childNode.childPointList.size() == 0 ) {

if (pointIndex[0][childPoint.index] != 0) {

childNode.value += pointIndex[0][childPoint.index];

if (childNode.value

minNode.value=childNode.value;

minNode.point=childNode.point;

minNode.parentNode=childNode.parentNode;

}

} else {

continue;

}

}

currentLiveNodeList.add(childNode);

}

}

currentLiveNodeList.remove(liveNode);

Collections.sort(currentLiveNodeList, new Comparator() {

@Override

public int compare(Node o1, Node o2) {

return o2.value-o1.value;

}

});

}

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

}

class Node{

private Node parentNode;

private Point point;

private List childNodeList=new ArrayList<>();

private List childPointList=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;

}

}

}

©著作权归作者所有:来自51CTO博客作者塞上名猪的原创作品,如需转载,请注明出处,否则将追究法律责任

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值