|
As shown:
4----------5
/| /|
/ | / |
0--|-------1 |
| | | |
| 6-------|--7
| / | /
|/ |/
2----------3
Find: the path from 0 to 1
#include <iostream.h>
const int MAX = 8;
//Create a matrix corresponding to the picture
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}};
/**
Detect the possibility of repeated cycles
*/
bool test(int s[], int length, int key)
{
for(int i=0; i<length; i++)
{
if(s[i] == key)
return false;
}
return true;
}
/**
start: starting point
end: 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) //Find the output path
{
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--; //Rewind
}
}
}
void main()
{
Search(0,1); //Find the path from 0 to 1
}
Output result:
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 |
|