参考了:
http://www.geeksforgeeks.org/backtracking-set-7-hamiltonian-cycle/
#include <stdio.h>
#define N 5
bool isSafe(int v,bool graph[N][N], int *path, int pos) {
if (graph[ path[pos - 1] ][v] == 0) return false;
for (int i = 0; i < pos; i++)
{
if (path[i] == v) return false;
}
return true;
}
bool hamCycleUtil(bool graph[N][N], int *path, int pos) {
if (pos == N) {
if (graph[path[pos - 1]][path[0]] == 1) {
return true;
}
else {
return false;
}
}
for (int i = 1; i < N; i++)
{
if (isSafe(i, graph, path, pos)) {
path[pos] = i;
if (hamCycleUtil(graph, path, pos + 1) == true)
return true;
path[pos] = -1;
}
}
}
bool hamCycle(bool graph[N][N]) {
int *path = new int[N];
for (int i = 0; i < N; i++)
{
path[i] = -1;
}
path[0];
if (hamCycleUtil(graph, path, 1) == false) {
printf("\nSolution does not exist");
return false;
}
printSolution(path);
return true;
}
/* A utility function to print solution */
void printSolution(int path[])
{
printf("Solution Exists:"
" Following is one Hamiltonian Cycle \n");
for (int i = 0; i < N; i++)
printf(" %d ", path[i]);
// Let us print the first vertex again to show the complete cycle
printf(" %d ", path[0]);
printf("\n");
}
int main()
{
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
bool graph1[N][N] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1 },
{ 0, 1, 0, 0, 1 },
{ 1, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 0 },
};
// Print the solution
hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
bool graph2[N][N] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1 },
{ 0, 1, 0, 0, 1 },
{ 1, 1, 0, 0, 0 },
{ 0, 1, 1, 0, 0 },
};
return 0;
}