c语言哈密顿路径算法,用于检查给定图中是否存在哈密顿循环或路径的C ++程序...
哈密頓循環(huán)是哈密頓路徑,因此從哈密頓路徑的最后一個頂點到第一個頂點有一條邊(在圖中)。它在無向圖中是一條路徑,該路徑恰好訪問該圖的每個頂點一次。
功能和目的: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)?{
//如果所有頂點都包含在哈密頓循環(huán)中
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
//圖是無向的循環(huán)周期
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
總結
以上是生活随笔為你收集整理的c语言哈密顿路径算法,用于检查给定图中是否存在哈密顿循环或路径的C ++程序...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 喝小青柑的功效与作用、禁忌和食用方法
- 下一篇: html assign无效,Object