Advertisement
dridk

Untitled

Nov 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3.  
  4. using namespace std;
  5.  
  6. // N x N chessboard
  7. #define N 8
  8.  
  9. // Below arrays details all 8 possible movements for a knight.
  10. // It is important to avoid changing sequence of below arrays
  11. int row[] = { 2, 1, -1, -2, -2, -1, 1, 2 , 2 };
  12. int col[] = { 1, 2, 2, 1, -1, -2, -2, -1, 1 };
  13.  
  14. // Check if (x, y) is valid chess board coordinates
  15. // Note that a knight cannot go out of the chessboard
  16. bool isValid(int x, int y)
  17. {
  18. if (x < 0 || y < 0 || x >= N || y >= N)
  19. return false;
  20.  
  21. return true;
  22. }
  23.  
  24. // Recursive function to perform the Knight's tour using backtracking
  25. void KnightTour(int visited[N][N], int x, int y, int pos)
  26. {
  27. // mark current square as visited
  28. visited[x][y] = pos;
  29.  
  30. // if all squares are visited, print the solution
  31. if (pos >= N*N)
  32. {
  33. for (int i = 0; i < N; i++)
  34. {
  35. for (int j = 0; j < N; j++)
  36. cout << visited[i][j] << " ";
  37. cout << endl;
  38. }
  39. cout << endl;
  40. // backtrack before returning
  41. visited[x][y] = 0;
  42. return;
  43. }
  44.  
  45. // check for all 8 possible movements for a knight
  46. // and recurse for each valid movement
  47. for (int k = 0; k < 8; k++)
  48. {
  49. // Get the new position of Knight from current
  50. // position on chessboard
  51. int newX = x + row[k];
  52. int newY = y + col[k];
  53.  
  54. // if new position is a valid and not visited yet
  55. if (isValid(newX, newY) && !visited[newX][newY])
  56. KnightTour(visited, newX, newY, pos + 1);
  57. }
  58.  
  59. // backtrack from current square and remove it from current path
  60. visited[x][y] = 0;
  61. }
  62.  
  63. // Print all Possible Knight's Tours in a chessboard
  64. int main()
  65. {
  66. // visited[][] serves two purpose -
  67. // 1. It keep track of squares involved the Knight's tour.
  68. // 2. It stores the order in which the squares are visited
  69. int visited[N][N];
  70.  
  71. // initialize visited[][] by 0 (unvisited)
  72. memset(visited, 0, sizeof visited);
  73.  
  74. int pos = 1;
  75.  
  76. // start knight tour from corner square (0, 0)
  77. KnightTour(visited, 1, 7, pos);
  78.  
  79. return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement