これは、グラフ内のハミルトニアン サイクルを見つけるための私のアルゴリズムです。
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;
}
最初のハミルトニアン サイクルを 1 つ見つけることができます。グラフで見つかったすべての可能なハミルトニアンサイクルを見つけるように適応させることは可能ですか?
入力は非対称行列 (ノード間の一部のリンクは一方向) であり、一部のノードは他のノードへの 2 つまたは 3 つのリンクを持つ場合があります。
ありがとうございました
編集:
明確にするために、アルゴリズムは既に解決策を見つけることができますが、2 番目の解決策を見つけることはできません。読んだところ、バックトラッキングを使用する A* で問題が解決する可能性がありますが、既に持っているものに追加できるかどうかはわかりません。