java实现旅行商问题_使用java写出旅行商问题,很难很难,求大佬们帮帮忙!

就用tsp 算法啊,TSP还不简单么,给你个案例package book;

import java.util.Scanner;

public class TSP {

static int n,m;//n城市数量,m边数量

static int grh[][];//地图

static int curentlength,bestlength;//当前距离,最短距离

static int curent[],best[];//当前路线,最好的路线

static int Max=Integer.MAX_VALUE;

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

n=sc.nextInt();

m=sc.nextInt();

grh=new int[n+1][n+1];

curent=new int[n+1];

best=new int[n+1];

curentlength=0;

bestlength=-1;

for(int i=1;i<=n;i++) {

curent[i]=i;

for(int j=1;j<=n;j++) {

grh[i][j]=Max;//初始化地图,每个点之间的距离都是无穷大

}

}

for(int i=1;i<=m;i++) {

int start = sc.nextInt();

int end = sc.nextInt();

int length = sc.nextInt();

grh[start][end]=length;

grh[end][start]=length;//把所有的边存储起来

}

backtrace(2);

if(bestlength!=-1) {

for(int i=1;i<=n;i++) {

System.out.print(best[i]+" ");

}

System.out.println("1");

System.out.println(bestlength);

}else {

System.out.println("-1");

}

}

private static void backtrace(int t) {

if(t==n) {

if(grh[curent[n-1]][curent[n]]!=Max&&grh[curent[n]][1]!=Max&&

(curentlength+grh[curent[n-1]][curent[n]]+grh[curent[n]][1]

//1.当到准备去第n个城市的时候,首先要判断当前售货员与第n个点有没有路线,没有路线就剪掉

//2.要判断第n个点与起点1有没有路线,没有也要剪掉

//3.判断走完这条路线,回到原点的总距离是不是小于已经知道的最短距离,如果大于也剪掉

//如果都符合,就要做更新操作

for(int i=1;i<=n;i++) {

best[i]=curent[i];

}

bestlength=curentlength+grh[curent[n-1]][curent[n]]+grh[curent[n]][1];

}

}else {

for(int i=t;i<=n;i++) {

if(grh[curent[t-1]][curent[i]]

//上面的剪枝条件是,t-1表示现在售货员所在的城市,i表示他现在要准备去的城市,两者之间必须要有边

//bestlength=-1表示第一次走

//符合条件我们就需要交换

swap(t,i);

curentlength=curentlength+grh[curent[t-1]][curent[t]];

backtrace(t+1);

curentlength=curentlength-grh[curent[t-1]][curent[t]];

swap(t,i);

}

}

}

}

private static void swap(int t, int i) {

int temp=0;

temp=curent[t];

curent[t]=curent[i];

curent[i]=temp;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值