package algrithms_hao;
import java.io.IOException;
import java.util.Scanner;
public class TSRP {
static int num;//顶点数
int x[];//存储路径
static int[] bestx;
float bestc;
float cc;
static float[][] a;//定义为全局变量
float traveling(int[] v) {
x = new int[num];
for (int i = 0; i < num; i++) {
x[i] = i;
}
bestc = Float.MAX_VALUE;
bestx = v;
backTrack(1);//从第二层开始便利
return bestc;
}
/*
www.quzhuanpan.com
去转盘网:转载请告知
*/
public void swap(int x[], int i, int j) {
int temp;
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
private void backTrack(int i) {
if (i == num - 1) {
if (a[x[num - 1]][x[num - 2]] < Float.MAX_VALUE
&& a[x[num - 1]][0] < Float.MAX_VALUE
&& (bestc == Float.MAX_VALUE || cc
+ a[x[num - 1]][x[num - 2]] + a[x[num - 1]][0] < bestc)) {//bestc最大时肯定要更新
for (int k = 0; k < num; k++) {
bestx[k] = x[k]+1;
}
bestc = cc + a[x[num - 1]][x[num - 2]] + a[x[num - 1]][0];
}
}
else {
for (int j = i; j < num; j++) {//i表示层数
if (a[x[j]][x[i - 1]]/* 和上一节点 */< Float.MAX_VALUE&& (bestc == Float.MAX_VALUE || cc + a[x[j]][x[i - 1]] < bestc)) {//剪枝
swap(x, i, j);
cc += a[x[j]][x[i - 1]];
backTrack(i + 1);
swap(x, i, j);
cc -= a[x[j]][x[i - 1]];
}
}
}
}
/*
www.quzhuanpan.com
去转盘网:转载请告知
*/
static public void initA() throws IOException{
a=new float[num][num];
for(int i=0;i<num;i++){
for(int j=0;j<num;j++){
a[i][j]=Float.MAX_VALUE;
}
}
System.out.println("建立权重关系(按exit结束)");
while(true){
Scanner sc=new Scanner(System.in);
String k=sc.next();
if(k.equals("exit")){
break;
}
String m=sc.next();
String l=sc.next();
int i=Integer.parseInt(k);
int j=Integer.parseInt(m);
float weight=Float.parseFloat(l);
a[i][j]=weight;
}
}
}
*************************************************************************************************
package algrithms_hao;
import java.io.IOException;
import java.util.Scanner;
public class Application {
public static void main(String args[]) throws IOException {
Scanner sc=new Scanner(System.in);
System.out.println("输入节点数目:");
TSRP.num =sc.nextInt();
int v[]=new int[TSRP.num];
for(int i=0;i<TSRP.num;i++){
v[i]=i+1;
}
TSRP tsrp = new TSRP();
TSRP.initA();
float bestResult=tsrp.traveling(v);
System.out.println("最优解:");
System.out.println(bestResult);
System.out.println("最优路径:");
for(int i=0;i<TSRP.num;i++){
System.out.print(TSRP.bestx[i]+" ");
}
}
}
转载于:https://blog.51cto.com/5912119/1734967