我写了一个类似于骑士之旅的程序,并决定尝试用同样的程序来解决骑士之旅,而不需要修改太多的代码。不幸的是,我没能做到,不是因为这不可能,而是我真的不知道问题出在哪里。我在网上查找了骑士之旅问题的其他程序,它们似乎也是基于同样的原理工作的。那我到底有什么问题
我运行了代码,什么都没有显示。基本上,递归一直在进行(它可能会在某个时候停止,但当我测试它时,它一直持续了3分钟,而实际上不应该超过1秒或2秒)。
#include <stdio.h>
#include <stdlib.h>
#define SIDE 8
#define VISITED 1
#define NOT_VISITED 0
#define FALSE 0
#define TRUE !FALSE
void printBoard(int board[][SIDE]);
int goHorsie(int board[][SIDE], int x, int y, int step);
int main(void)
{
int board[SIDE][SIDE] = { NOT_VISITED };
if (goHorsie(board, 0, 0, 1))
{
printf("Yes, the knight\'s tour problem is possible, here is the result:\n");
printBoard(board);
}
else
{
printf("No, the knight\'s tour problem is not possible.\n");
}
return 0;
}
/*
This function checks if knight can travel through the entire board while only stepping on every square once.
input: the board, the position's x and y, and current step.
output: whether a path was found.
*/
int goHorsie(int board[][SIDE], int x, int y, int step)
{
int res = FALSE;
if (step == (SIDE * SIDE + 1))
{
res = TRUE;
}
else if (x >= SIDE || y >= SIDE || x < 0 || y < 0 || // out of the board
board[x][y] != NOT_VISITED) // we were here already!
{
res = FALSE;
}
else
{
board[x][y] = step;
step++;
// changing order here will change the path, because once a condition is verified (TRUE) the rest aren't checked
res = goHorsie(board, x + 2, y + 1, step) ||
goHorsie(board, x + 2, y - 1, step) ||
goHorsie(board, x + 1, y + 2, step) ||
goHorsie(board, x + 1, y - 2, step) ||
goHorsie(board, x - 2, y + 1, step) ||
goHorsie(board, x - 2, y - 1, step) ||
goHorsie(board, x - 1, y + 2, step) ||
goHorsie(board, x - 1, y - 2, step);
if (!res)
{
board[x][y] = NOT_VISITED;
}
}
return res;
}
/*
This function prints the board.
input: board to print.
output: none.
*/
void printBoard(int board[][SIDE])
{
int i = 0, j = 0;
for (i = 0; i < SIDE; i++)
{
for (j = 0; j < SIDE; j++)
{
printf("%3d", board[i][j]);
}
printf("\n"); // go down a line
}
}
1条答案
按热度按时间mzillmmw1#
你的代码没有明显的错误。它将以一个解决方案结束。最终会的在尝试了1050个动作之后。你需要一个更好的启发式来选择下一步。查看维基百科上关于Warnsdorff规则的页面。