贪心算法解决TSP问题 java代码
时间: 2023-08-30 11:10:50 浏览: 105
以下是贪心算法解决TSP问题的Java代码:
```java
public class TSPGreedyAlgorithm {
private final int[][] graph;
public TSPGreedyAlgorithm(int[][] graph) {
this.graph = graph;
}
public List<Integer> solve() {
List<Integer> path = new ArrayList<>();
boolean[] visited = new boolean[graph.length];
int current = 0;
visited[current] = true;
path.add(current + 1);
while (path.size() < graph.length) {
int next = getNextCity(current, visited);
visited[next] = true;
path.add(next + 1);
current = next;
}
path.add(1);
return path;
}
private int getNextCity(int current, boolean[] visited) {
int next = -1;
int minCost = Integer.MAX_VALUE;
for (int i = 0; i < graph.length; i++) {
if (i != current && !visited[i] && graph[current][i] < minCost) {
next = i;
minCost = graph[current][i];
}
}
return next;
}
}
```
注:此贪心算法解决的是TSP问题的近似解,不一定是最优解。
阅读全文