C中的Knight's Tour问题对我不起作用

jaql4c8m  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(96)

我写了一个类似于骑士之旅的程序,并决定尝试用同样的程序来解决骑士之旅,而不需要修改太多的代码。不幸的是,我没能做到,不是因为这不可能,而是我真的不知道问题出在哪里。我在网上查找了骑士之旅问题的其他程序,它们似乎也是基于同样的原理工作的。那我到底有什么问题
我运行了代码,什么都没有显示。基本上,递归一直在进行(它可能会在某个时候停止,但当我测试它时,它一直持续了3分钟,而实际上不应该超过1秒或2秒)。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define SIDE 8
  4. #define VISITED 1
  5. #define NOT_VISITED 0
  6. #define FALSE 0
  7. #define TRUE !FALSE
  8. void printBoard(int board[][SIDE]);
  9. int goHorsie(int board[][SIDE], int x, int y, int step);
  10. int main(void)
  11. {
  12. int board[SIDE][SIDE] = { NOT_VISITED };
  13. if (goHorsie(board, 0, 0, 1))
  14. {
  15. printf("Yes, the knight\'s tour problem is possible, here is the result:\n");
  16. printBoard(board);
  17. }
  18. else
  19. {
  20. printf("No, the knight\'s tour problem is not possible.\n");
  21. }
  22. return 0;
  23. }
  24. /*
  25. This function checks if knight can travel through the entire board while only stepping on every square once.
  26. input: the board, the position's x and y, and current step.
  27. output: whether a path was found.
  28. */
  29. int goHorsie(int board[][SIDE], int x, int y, int step)
  30. {
  31. int res = FALSE;
  32. if (step == (SIDE * SIDE + 1))
  33. {
  34. res = TRUE;
  35. }
  36. else if (x >= SIDE || y >= SIDE || x < 0 || y < 0 || // out of the board
  37. board[x][y] != NOT_VISITED) // we were here already!
  38. {
  39. res = FALSE;
  40. }
  41. else
  42. {
  43. board[x][y] = step;
  44. step++;
  45. // changing order here will change the path, because once a condition is verified (TRUE) the rest aren't checked
  46. res = goHorsie(board, x + 2, y + 1, step) ||
  47. goHorsie(board, x + 2, y - 1, step) ||
  48. goHorsie(board, x + 1, y + 2, step) ||
  49. goHorsie(board, x + 1, y - 2, step) ||
  50. goHorsie(board, x - 2, y + 1, step) ||
  51. goHorsie(board, x - 2, y - 1, step) ||
  52. goHorsie(board, x - 1, y + 2, step) ||
  53. goHorsie(board, x - 1, y - 2, step);
  54. if (!res)
  55. {
  56. board[x][y] = NOT_VISITED;
  57. }
  58. }
  59. return res;
  60. }
  61. /*
  62. This function prints the board.
  63. input: board to print.
  64. output: none.
  65. */
  66. void printBoard(int board[][SIDE])
  67. {
  68. int i = 0, j = 0;
  69. for (i = 0; i < SIDE; i++)
  70. {
  71. for (j = 0; j < SIDE; j++)
  72. {
  73. printf("%3d", board[i][j]);
  74. }
  75. printf("\n"); // go down a line
  76. }
  77. }
mzillmmw

mzillmmw1#

你的代码没有明显的错误。它将以一个解决方案结束。最终会的在尝试了1050个动作之后。你需要一个更好的启发式来选择下一步。查看维基百科上关于Warnsdorff规则的页面。

相关问题