马踏棋盘算法怎么我感觉一直死循环啊。。
#include <stdio.h>#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_VERTEX_NUM 10
#define X 5
#define Y 5
int chess;
int nextxy(int *x, int *y, int count)
{
switch (count)
{
case 0:
if (*x + 2 <= X - 1 && *y - 1 >= 0 && chess[*x + 2][*y - 1] == 0)
{
*x = *x + 2;
*y = *y - 1;
return 1;
}
break;
case 1:
if (*x + 2 <= X - 1 && *y + 1 <= Y - 1 && chess[*x + 2][*y + 1] == 0)
{
*x = *x + 2;
*y = *y + 1;
return 1;
}
break;
case 2:
if (*x + 1 <= X - 1 && *y - 2 >= 0 && chess[*x + 1][*y - 2] == 0)
{
*x = *x + 1;
*y = *y - 2;
return 1;
}
break;
case 3:
if (*x + 1 <= X - 1 && *y + 2 <= Y - 1 && chess[*x + 1][*y + 2] == 0)
{
*x = *x + 1;
*y = *y + 2;
return 1;
}
break;
case 4:
if (*x - 2 >= 0 && *y - 1 >= 0 && chess[*x - 2][*y - 1] == 0)
{
*x = *x - 2;
*y = *y - 1;
return 1;
}
break;
case 5:
if (*x - 2 >= 0 && *y + 1 <= Y - 1 && chess[*x - 2][*y + 1] == 0)
{
*x = *x - 2;
*y = *y + 1;
return 1;
}
break;
case 6:
if (*x - 1 >= 0 && *y - 2 >= 0 && chess[*x - 1][*y - 2] == 0)
{
*x = *x - 1;
*y = *y - 2;
return 1;
}
break;
case 7:
if (*x - 1 >= 0 && *y + 2 <= Y - 1 && chess[*x - 1][*y + 2] == 0)
{
*x = *x - 1;
*y = *y + 2;
return 1;
}
break;
default:
break;
}
return 0;
}
void print() {
int i, j;
for (i = 0; i < X; i++)
{
for (j = 0; j < Y; j++)
{
printf("%2d\t", chess);
}
printf("\n");
}
printf("\n");
}
long h = 0;
int travechess(int x, int y, int tag) {
printf("当前外层x:%d,当前外层y:%d,当前tag:%d\n",x, y, tag);
chess = tag;
int x1 = x, y1 = y, flag = 0,count=0;
if (tag == X*Y)
{
print();
return 1;
}
flag = nextxy(&x1, &y1, count);
while (count<7 && flag==0)
{
count++;
flag = nextxy(&x1, &y1, count);
}
while (flag==1)
{
if (travechess(x1, y1, tag + 1)) {
return 1;
};
count++;
x1 = x;
y1 = y;
flag = nextxy(&x1, &y1, count);
while (count<7 && flag == 0)
{
count++;
flag = nextxy(&x1, &y1, count);
}
}
if (flag==0)
{
chess =0;
}
return 0;
}
int main() {
int i, j;
clock_t start, finish;
start = clock();
for (i = 0; i < X; i++)
{
for (j = 0; j < Y; j++)
{
chess = 0;
}
}
if (!travechess(2, 0, 1))
{
printf("bao qian,shi bai le");
}
finish = clock();
printf("\nben ci ji suan shi jian:%fmiao\n\n", (double)((finish - start) /CLOCKS_PER_SEC));
return 0;
}
看了小甲鱼的马踏棋盘算法,然后模仿着自己写了一个,完全自己写的,然后感觉很多时候都是死循环,一直没结果。。。就算5*5的棋盘都是,有时又有结果,怎么回事啊,我电脑是7700k,4.5g,的cpu,应该很快啊,这种算法都这么慢啊!! 有人吗?鱼油呢
页:
[1]