这是我在图中找到哈密顿循环的算法:
private SolutionArray solution;
private int V, pathCount;
private int[] path;
private int[][] graph;
/**
* Constructor
*/
public ConcreteSolver() {
solution = new SolutionArray();
}
@Override
public SolutionArray solve(PathMatrix input) {
V = input.getNbVertex();
path = new int[V];
/** Set all path to non-visited **/
boolean[] visited = new boolean[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
Arrays.fill(path, -1);
graph = input.getMatrix();
try {
path[0] = input.getFirstVertex();
pathCount = 1;
findPaths(0);
System.out.println("No solution");
} catch (Exception e) {
System.out.println("\nSolution found");
//input.printMatrix();
displayAndWrite();
}
return solution;
}
/**
* function to find paths recursively
*/
private void findPaths(int vertex) throws Exception {
/** solution **/
if (graph[vertex][0] >= 1 && pathCount == V) {
throw new Exception();
}
/** all vertices selected but last vertex not linked to 0 **/
if (pathCount == V)
return;
for (int v = 0; v < V; v++) {
/** if connected **/
if (graph[vertex][v] >= 1) {
/** add to path **/
path[pathCount++] = v;
/** if vertex not already selected solve recursively **/
if (!isPresent(v))
findPaths(v);
/** remove path **/
path[--pathCount] = -1;
}
}
}
/**
* function to check if path is already selected
*/
private boolean isPresent(int v) {
for (int i = 0; i < pathCount - 1; i++)
if (path[i] == v)
return true;
return false;
}
我能够找到一个第一个哈密顿循环。是否可以对其进行调整以找到图中所有可能的哈密顿循环?
输入是一个非对称矩阵(节点之间的一些链接是一种方式),一些节点可能有 2 或 3 个链接到其他节点。
谢谢
编辑:
澄清一下,该算法已经可以找到解决方案,但找不到第二个解决方案,依此类推。从阅读中,使用 bactracking 的 A* 可能会解决问题,但我不确定它是否可以添加到我已有的内容中。