fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 8
  4.  
  5. int main() {
  6. int board[SIZE][SIZE] = {0};
  7. int accessibility[SIZE][SIZE] = {
  8. {2, 3, 4, 4, 4, 4, 3, 2},
  9. {3, 4, 6, 6, 6, 6, 4, 3},
  10. {4, 6, 8, 8, 8, 8, 6, 4},
  11. {4, 6, 8, 8, 8, 8, 6, 4},
  12. {4, 6, 8, 8, 8, 8, 6, 4},
  13. {4, 6, 8, 8, 8, 8, 6, 4},
  14. {3, 4, 6, 6, 6, 6, 4, 3},
  15. {2, 3, 4, 4, 4, 4, 3, 2}
  16. };
  17.  
  18. int horizontal[8] = {2, 1, -1, -2, -2, -1, 1, 2};
  19. int vertical[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
  20.  
  21. int startRow = 0;
  22. int startCol = 0;
  23. int currentRow = startRow;
  24. int currentCol = startCol;
  25. board[currentRow][currentCol] = 1;
  26.  
  27. int moveNumber;
  28. for (moveNumber = 2; moveNumber <= 64; moveNumber++) {
  29. int minAccess = 9;
  30. int bestMove = -1;
  31. int nextRow = -1;
  32. int nextCol = -1;
  33.  
  34. for (int moveType = 0; moveType < 8; moveType++) {
  35. int testRow = currentRow + vertical[moveType];
  36. int testCol = currentCol + horizontal[moveType];
  37.  
  38. if (testRow >= 0 && testRow < SIZE && testCol >= 0 && testCol < SIZE) {
  39. if (board[testRow][testCol] == 0) {
  40. if (accessibility[testRow][testCol] < minAccess) {
  41. minAccess = accessibility[testRow][testCol];
  42. bestMove = moveType;
  43. nextRow = testRow;
  44. nextCol = testCol;
  45. }
  46. }
  47. }
  48. }
  49.  
  50. if (bestMove != -1) {
  51. currentRow = nextRow;
  52. currentCol = nextCol;
  53. board[currentRow][currentCol] = moveNumber;
  54.  
  55. for (int moveType = 0; moveType < 8; moveType++) {
  56. int testRow = currentRow + vertical[moveType];
  57. int testCol = currentCol + horizontal[moveType];
  58. if (testRow >= 0 && testRow < SIZE && testCol >= 0 && testCol < SIZE) {
  59. accessibility[testRow][testCol]--;
  60. }
  61. }
  62. } else {
  63. break;
  64. }
  65. }
  66.  
  67. for (int r = 0; r < SIZE; r++) {
  68. for (int c = 0; c < SIZE; c++) {
  69. printf("%2d ", board[r][c]);
  70. }
  71. printf("\n");
  72. }
  73.  
  74. if (moveNumber > 64) {
  75. int isClosed = 0;
  76. for (int moveType = 0; moveType < 8; moveType++) {
  77. if (currentRow + vertical[moveType] == startRow && currentCol + horizontal[moveType] == startCol) {
  78. isClosed = 1;
  79. break;
  80. }
  81. }
  82. if (isClosed) {
  83. printf("\nThis is a closed tour!\n");
  84. } else {
  85. printf("\nThis is a full tour, but not closed.\n");
  86. }
  87. } else {
  88. printf("\nFull tour not achieved. Reached move %d.\n", moveNumber - 1);
  89. }
  90.  
  91. return 0;
  92. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
 1 22  3 18 25 30 13 16 
 4 19 24 29 14 17 34 31 
23  2 21 26 35 32 15 12 
20  5 56 49 28 41 36 33 
57 50 27 42 61 54 11 40 
 6 43 60 55 48 39 64 37 
51 58 45  8 53 62 47 10 
44  7 52 59 46  9 38 63 

This is a full tour, but not closed.