|
| Class Cities { private int[][] cities; //各城市表示为(X,Y)X,Y为0到99之间的值 private int[] shortestPath; //保存最短路程对应的经历顺序 private int num; //保存N(城市个数) private long shortestLength = 100000000;//N个城市遍历时可能最大路程 private long getLength(int[] tPath) {...} //计算以tPath为经历顺序的路程 public Cities(int n) //构造n个城市的坐标,假设为0到99之间的随机数 { ... } public int[] getShortestPath() //获得最短路径 { int[] tempPath = new int[num]; shortestPath = new int[num]; int[] citiesToured = new int[num]; //保存第I个城市是否已经经历 int citiesNum = 0; //已经经历城市的个数 for(int i=0; i<num; i++) citiesToured[i] = 0; goThrough(tempPath, citiesNum, citiesToured);//遍历各城市 for(int i=0; i<num; i++) tempPath[i] = shortestPath[i]; //得到遍历顺序 return tempPath; //返回结果 } private void goThrough(int[] tPath, int cNum, int[] cToured) //遍历N个城市 { if (cNum == 0) //无经历城市时,选择第1个城市 { cNum++; tPath[0] = 0; cToured[0] = 1; goThrough(tPath, cNum, cToured); } else if (cNum == num) //各个城市已经经历,结束 { long tempLength = getLength(tPath);//计算此经历顺序所走的路程 if (tempLength < shortestLength) //比较路程 { shortestLength = tempLength; //更新最短路程及其经历顺序 for(int i=0; i<num; i++) shortestPath[i] = tPath[i]; } } else { for(int i=0; i<num; i++) if (cToured[i] != 1) //选择未经历的城市 { cToured[i] = 1; //加入已经历城市 tPath[cNum]= i; cNum++; //已经历城市个数+1 goThrough(tPath, cNum, cToured);//调用下一层 cToured[i] = 0; //恢复本层的状态: cNum--; //已经历城市及个数 } //End if in for(i) } //End else } private long getLength(int[] tPath) //以指定顺序计算遍历路程 { long length = 0; //路程 int nowPoint = 0; //当前城市,第一次取0 for(int i=1; i<num; i++) { int j = tPath[i]; length+=(long)Math.sqrt((cities[j][0]-cities[nowPoint][0])*(cities[j][0]-cities[nowPoint][0])+(cities[j][1]-cities[nowPoint][1])*(cities[j][1]-cities[nowPoint][1]));//加上当前、下一城市间的距离 nowPoint = j; //更新当前城市 } length+=(long)Math.sqrt((cities[0][0]-cities[nowPoint][0])*(cities[0][0]-cities[nowPoint][0]) +(cities[0][1]-cities[nowPoint][1])*(cities[0][1]-cities[nowPoint][1]));//加上首尾城市间的距离 return length; } } // Cities类定义结束 |