|
发表于 2020-8-14 18:15:02
|
显示全部楼层
如图:
4----------5
/| /|
/ | / |
0--|-------1 |
| | | |
| 6-------|--7
| / | /
|/ |/
2----------3
求:0 到 1 的路径
#include <iostream.h>
const int MAX = 8;
//建立与图对应的距阵
int num[MAX][MAX]={{1,1,1,0,1,0,0,0}, {1,1,0,1,0,1,0,0},{1,0,1,1,0,0,1,0},
{0,1,1,1,0,0,0,1},{1,0,0,0,1,1,1,0},{0,1,0,0,1,1,0,1},{0,0,1,0,1,0,1,1},
{0,0,0,1,0,1,1,1}};
/**
检测重复循环的可能
*/
bool test(int s[], int length, int key)
{
for(int i=0; i<length; i++)
{
if(s[i] == key)
return false;
}
return true;
}
/**
start:起始点
end:终点
*/
void Search(int start, int end)
{
int top = 0;
int d[MAX]={0};
int s[MAX] = {0};
bool is = true;
d[top] = start;
while(top > -1)
{
is = true;
while(s[d[top]]++ < MAX)
{
if(d[top] != s[d[top]]-1 && num[d[top]][s[d[top]]-1] == 1)
{
if(s[d[top]]-1 == end) //找到输出路径
{
for(int i=0; i<=top; i++)
{
cout<<d[i]<<' ';
}
cout<<end<<endl;
}
else
{
if(test(d, top, s[d[top]]-1))
{
top++;
d[top] = s[d[top-1]]-1;
s[d[top]] = 0;
is = false;
break;
}
}
}
}
if(is == true)
{
top--; //回朔
}
}
}
void main()
{
Search(0,1); //求 0 到 1 的路径
}
输出结果:
0 1
0 2 3 1
0 2 3 7 5 1
0 2 3 7 6 4 5 1
0 2 6 4 5 1
0 2 6 4 5 7 3 1
0 2 6 7 3 1
0 2 6 7 5 1
0 4 5 1
0 4 5 7 3 1
0 4 5 7 6 2 3 1
0 4 6 2 3 1
0 4 6 2 3 7 5 1
0 4 6 7 3 1
0 4 6 7 5 1
Press any key to continue |
|