日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時間:2023/12/4 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 ++程序...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。