汉密尔顿最短路径用java语言编写
时间: 2023-09-09 16:11:18 浏览: 86
用Java编写的最短路径代码
3星 · 编辑精心推荐
下面是一个用Java语言编写的解决汉密尔顿最短路径的算法示例:
```java
import java.util.Arrays;
public class HamiltonianPath {
private int[][] graph;
private int[] path;
private boolean[] visited;
private int n;
private int minDist;
public HamiltonianPath(int[][] graph) {
this.graph = graph;
this.n = graph.length;
this.path = new int[n];
this.visited = new boolean[n];
Arrays.fill(visited, false);
this.minDist = Integer.MAX_VALUE;
}
public int findMinDist() {
visited[0] = true;
path[0] = 0;
dfs(1, 0);
return minDist;
}
private void dfs(int depth, int dist) {
if (depth == n) {
minDist = Math.min(minDist, dist + graph[path[n - 1]][0]);
return;
}
for (int i = 1; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
path[depth] = i;
dfs(depth + 1, dist + graph[path[depth - 1]][i]);
visited[i] = false;
}
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 2, 9, 10},
{1, 0, 6, 4},
{15, 7, 0, 8},
{6, 3, 12, 0}
};
HamiltonianPath hp = new HamiltonianPath(graph);
System.out.println("The minimum distance is: " + hp.findMinDist());
}
}
```
在这个示例中,我们使用了深度优先搜索算法来遍历所有可能的路径,并计算出每条路径的长度。对于每个节点,我们遍历未访问的节点,并将其添加到路径中,然后递归地继续搜索下一个节点。最终,我们找到一条包含所有节点的路径,并计算出其长度,然后将其与当前的最小路径长度进行比较,更新最小路径长度。
阅读全文