|
8 | 8 | * @author lyq
|
9 | 9 | *
|
10 | 10 | */
|
11 |
| -public class Ant implements Comparable<Ant>{ |
12 |
| - //蚂蚁当前所在城市 |
| 11 | +public class Ant implements Comparable<Ant> { |
| 12 | + // 蚂蚁当前所在城市 |
13 | 13 | String currentPos;
|
14 | 14 | // 蚂蚁遍历完回到原点所用的总距离
|
15 | 15 | Double sumDistance;
|
@@ -51,41 +51,72 @@ public double calSumDistance() {
|
51 | 51 |
|
52 | 52 | return sumDistance;
|
53 | 53 | }
|
54 |
| - |
| 54 | + |
55 | 55 | /**
|
56 | 56 | * 蚂蚁选择前往下一个城市
|
| 57 | + * |
57 | 58 | * @param city
|
58 |
| - * 所选的城市 |
| 59 | + * 所选的城市 |
59 | 60 | */
|
60 |
| - public void goToNextCity(String city){ |
| 61 | + public void goToNextCity(String city) { |
61 | 62 | this.currentPath.add(city);
|
62 | 63 | this.currentPos = city;
|
63 | 64 | this.nonVisitedCitys.remove(city);
|
64 | 65 | this.visitedCitys.add(city);
|
65 | 66 | }
|
66 |
| - |
| 67 | + |
67 | 68 | /**
|
68 | 69 | * 判断蚂蚁是否已经又重新回到起点
|
| 70 | + * |
69 | 71 | * @return
|
70 | 72 | */
|
71 |
| - public boolean isBack(){ |
| 73 | + public boolean isBack() { |
72 | 74 | boolean isBack = false;
|
73 | 75 | String startPos;
|
74 | 76 | String endPos;
|
75 |
| - |
76 |
| - if(currentPath.size() == 0){ |
| 77 | + |
| 78 | + if (currentPath.size() == 0) { |
77 | 79 | return isBack;
|
78 | 80 | }
|
79 |
| - |
| 81 | + |
80 | 82 | startPos = currentPath.get(0);
|
81 |
| - endPos = currentPath.get(currentPath.size()-1); |
82 |
| - if(currentPath.size() > 1 && startPos.equals(endPos)){ |
| 83 | + endPos = currentPath.get(currentPath.size() - 1); |
| 84 | + if (currentPath.size() > 1 && startPos.equals(endPos)) { |
83 | 85 | isBack = true;
|
84 | 86 | }
|
85 |
| - |
| 87 | + |
86 | 88 | return isBack;
|
87 | 89 | }
|
88 | 90 |
|
| 91 | + /** |
| 92 | + * 判断蚂蚁在本次的走过的路径中是否包含从城市i到城市j |
| 93 | + * |
| 94 | + * @param cityI |
| 95 | + * 城市I |
| 96 | + * @param cityJ |
| 97 | + * 城市J |
| 98 | + * @return |
| 99 | + */ |
| 100 | + public boolean pathContained(String cityI, String cityJ) { |
| 101 | + String lastCity; |
| 102 | + String currentCity; |
| 103 | + boolean isContained = false; |
| 104 | + |
| 105 | + for (int i = 0; i < currentPath.size() - 1; i++) { |
| 106 | + lastCity = currentPath.get(i); |
| 107 | + currentCity = currentPath.get(i + 1); |
| 108 | + |
| 109 | + // 如果某一段路径的始末位置一致,则认为有经过此城市 |
| 110 | + if ((lastCity.equals(cityI) && currentCity.equals(cityJ)) |
| 111 | + || (lastCity.equals(cityJ) && currentCity.equals(cityI))) { |
| 112 | + isContained = true; |
| 113 | + break; |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + return isContained; |
| 118 | + } |
| 119 | + |
89 | 120 | @Override
|
90 | 121 | public int compareTo(Ant o) {
|
91 | 122 | // TODO Auto-generated method stub
|
|
0 commit comments