请问这种叫什么算法?
描述:有一个 W * H (上图是 5 * 3)的表格,从任意一个格子出发,每次走一相邻的格子,不重复遍历所有的格子。如果不能遍历所有,则要求算出最长的一条路径。
本来想找找别人的贴。但好多是说骑士遍历,跟这个不同。
又不知道这种叫什么算法,要怎么求。请帮忙写一写算法过程。
[ 本帖最后由 asianh 于 2011-5-8 06:27 编辑 ]
2011-05-08 06:24
2011-05-08 08:54
2011-05-08 10:47
2011-05-08 12:07
程序代码:#include <stdio.h>
#include <time.h>
#define WIDTH 5
#define HEIGHT 3
struct point
{
int x;
int y;
};
struct point moving[4] =
{
{1, 0}, //沿着x轴正向移动
{0, 1}, //沿着y轴正向移动
{-1, 0}, //沿着x轴反向移动
{0, -1}, //沿着y轴反向移动
};
int map[HEIGHT][WIDTH] = {0};
int get_xy(int M)
{
srand(time(NULL));
return rand()%M;
}
/*
*参数p表示将要标记的点 即在程序的执行当中标记1 表示已经
*遍历过 *counter表示计数器 计数器满后则程序退出。
*/
int deal(struct point p, int *counter)
{
struct point temp;
int i = 0;
//标记
map[p.y][p.x] = 1;
if (++*counter == WIDTH*HEIGHT)
{
return 1;
}
for ( ; i<4; ++i )
{
temp.x = p.x + moving[i].x;
temp.y = p.y + moving[i].y;
if (temp.x>=0 && temp.x<WIDTH &&
temp.y<HEIGHT && temp.y>=0 &&
!map[temp.y][temp.x])
{
if (deal(temp, counter))
{
printf("(%d, %d) ", temp.x, temp.y);
return 1;
}
}
}
if ( i==4 )
{
--*counter;
}
return 0;
}
int main(void)
{
int counter = 0;
struct point p;
p.x = get_xy(WIDTH);
p.y = get_xy(HEIGHT);
deal(p, &counter);
if ( counter == 15 )
{
printf("(%d, %d)\n", p.x, p.y);
}
return 0;
}
2011-05-08 13:41
2011-05-08 17:07