Advertisement
193030

kursvoa AI WIP

Mar 16th, 2022
54
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None
  1. #include <iostream>
  2. #include <stdio.h>
  3. #define BOARD_SIZE 4
  4. #define DIRECTIONS 8
  5. #define UNVISITED -1
  6. using namespace std;
  7. int board[BOARD_SIZE][BOARD_SIZE];
  8.  
  9. //int xDir[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
  10. //int yDir[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
  11. int xDir[] = { -1,-2, -2, -1, 1, 2, 1, 2 };
  12. int yDir[] = { -2,-1, 1, 2, -2, -1, 2, 1 };
  13. static int iterations = 5;
  14. void printBoard()
  15. {
  16. for (int i = 0; i < BOARD_SIZE; i++)
  17. {
  18. for (int j = 0; j < BOARD_SIZE; j++)
  19. {
  20. if(board[i][j] !=0)
  21. printf(" %02d", board[i][j]-4);
  22. else
  23. printf(" %02d", board[i][j]);
  24.  
  25. }
  26. cout << endl;
  27. }
  28. }
  29. void initializeBoard()
  30. {
  31. for (int i = 0; i < BOARD_SIZE; i++)
  32. {
  33. for (int j = 0; j < BOARD_SIZE; j++)
  34. {
  35. board[i][j] = UNVISITED;
  36. }
  37. }
  38. board[0][0] = 0;
  39. board[0][3] = 0;
  40. board[3][3] = 0;
  41. board[3][0] = 0;
  42.  
  43.  
  44. }
  45. void printSolution()
  46. {
  47. cout << "Printing the solution" << endl;
  48. printBoard();
  49. }
  50. int isMovePossible(int x, int y)
  51. {
  52. if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
  53. return false;
  54. }
  55. else {
  56. cout << "The move is possible " << endl;
  57. return true;
  58. }
  59. }
  60. int solveProblem(int x, int y) {
  61. if (iterations == BOARD_SIZE * BOARD_SIZE)
  62. {
  63.  
  64. return 1;
  65. }
  66. for (int i = 0; i < DIRECTIONS; i++)
  67. {
  68. int nextX = x + xDir[i];
  69. int nextY = y + yDir[i];
  70. if (isMovePossible(nextX, nextY) && board[nextX][nextY]== UNVISITED) {
  71.  
  72. board[nextX][nextY] = iterations;
  73. iterations++;
  74. if (solveProblem(nextX, nextY)) {
  75. return true;
  76. }
  77. iterations--;
  78. board[nextX][nextY] = UNVISITED; //backtrack
  79. }
  80. }
  81.  
  82. return false;
  83. }
  84. void solve()
  85. {
  86. board[0][2] = 0; // starting position 0,0
  87. if (solveProblem(0,2))
  88. {
  89. printSolution();
  90. }
  91. else
  92. {
  93. cout << "There are no solutions for this problem" << endl;
  94. printBoard();
  95. }
  96. }
  97. int main()
  98. {
  99.  
  100. initializeBoard();
  101. solve();
  102. }
Advertisement
RAW Paste Data Copied
Advertisement