This is my algorithm to find a Hamiltonian cycle in a graph:
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;
}
I'm able to find a single first Hamiltonian cycle. Is it possible to adapt it to find all possible Hamiltonian cycles found in the graph?
The input is a non-symmetrical matrix (some links between nodes are one way) and some nodes may have 2 or 3 links to other nodes.
Thank you
EDIT:
To clarify, the algorithm can already find a solution but cannot find a second one and so on. From reading, A* using bactracking might solve the issue but I'm not sure if it can be added to what I already have.