c语言哈密顿路径算法,用于检查给定图中是否存在哈密顿循环或路径的C ++程序...

哈密顿循环是哈密顿路径,因此从哈密顿路径的最后一个顶点到第一个顶点有一条边(在图中)。它在无向图中是一条路径,该路径恰好访问该图的每个顶点一次。

功能和目的:Begin

1.function isSafe() is used to check for whether it is adjacent to the previously added vertex and already not added.

2. function hamiltonianCycle() solves the hamiltonian problem.

3. function hamCycle() uses hamiltonianCycle() to solve the hamiltonian problem.

It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path.

End

示例#include 

#include 

#include 

#define N 5

using namespace std;

void displaytheSolution(int path[]);

bool isSafe(int n, bool g[N][N], int path[], int pos) {

if (g [path[pos-1]][n] == 0)

return false;

for (int i = 0; i 

if (path[i] == n)

return false;

return true;

}

bool hamiltonianCycle(bool g[N][N], int path[], int pos) {

//如果所有顶点都包含在哈密顿循环中

if (pos == N) {

if (g[ path[pos-1] ][ path[0] ] == 1)

return true;

else

return false;

}

for (int n = 1; n 

if (isSafe(n, g, path, pos)) //Check if this vertex can be added to Hamiltonian Cycle

{

path[pos] = n;

//重复构建其余路径

if (hamiltonianCycle (g, path, pos+1) == true)

return true;

path[pos] = -1; //remove vertex if it doesn’t lead to the solution

}

}

return false;

}

bool hamCycle(bool g[N][N]) {

int *path = new int[N];

for (int i = 0; i 

path[i] = -1;

//将顶点0作为路径中的第一个顶点。

If there is a Hamiltonian Cycle, then the path can be started from any point

//图是无向的循环周期

path[0] = 0;

if (hamiltonianCycle(g, path, 1) == false) {

cout<

return false;

}

displaytheSolution(path);

return true;

}

void displaytheSolution(int p[]) {

cout<

cout<

for (int i = 0; i 

cout<

cout<

}

int main() {

bool g[N][N] = {

{0, 1, 0, 1, 1},

{0, 0, 1, 1, 0},

{0, 1, 0, 1, 1},

{1, 1, 1, 0, 1},

{0, 1, 1, 0, 0},

};

hamCycle(g);

return 0;

}

输出结果存在周期: Following is one Hamiltonian Cycle

0 4 1 2 3 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值