/*
采用贪心法求解巡回售货员问题。设有n个城市。巡回售货员现在某城市。请为此售货员设计一回路,
让售货员访问每个城市一次,且仅一次,并返回出发城市,并且使回路路径长度最短。
*/
public class Greedy {
int[][] array; //各城市距离 0,1...n 分别表示0号城市,1号城市。。。。n号城市。设自己到自己为无穷。
int len=array[0].length; //得到城市的个数
boolean [] mark=new boolean [len]; //设置一个标志数组,记录是否该城市已经访问
int [] trace=new int[len]; //纪录售货员路径,
//构造函数,初始化
Greedy(){
array= new InputArray().getArray(); //得到各城市的距离
for(int i=0;i<len;i++) //初始化标志数组为false
mark[i]=false;
}
//得到最短路经算法
void getShortcut(){
trace[0]=0; //假设从0号城市出发
mark[0]=true;
int i=pass(0);
for(int j=1;j<len;j++)
{ mark[i]=true;
i=pass(i);
trace[j-1] = i;
}
trace[len]=array[i][0];
}
// 经过某城市处理,找出下一个要走的城市
int pass(int i){
int temp=1000;
int k=0;
for(int j=0;j<len;j++)
if(mark[j]&&temp>array[i][j])
{temp=array[i][j];
k=j;
}
return k;
}
public static void main(String[] args) {
Greedy Gr=new Greedy();
int sum=0;
System.out.print("最短路径为:");
for(int i=0;i<Gr.len;i++){
System.out.print(Gr.trace[i] + " ");
sum+=Gr.trace[i];
}
System.out.println("/n总路径长:"+sum);
}
}
调试时提醒 array= new InputArray().getArray(); 有错,我不知道哪里错了