Hamiltonian Cycle (backtracing: 2^n)

参考了:

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值