fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. const int row[8] = {-2, -1, +1, +2, +2, +1, -1, -2};
  6. const int col[8] = {+1, +2, +2, +1, -1, -2, -2, -1};
  7.  
  8. void try2Move(int count, int x, int y, int** board, int n);
  9. void printAns(int** board, int n);
  10. bool isInBoard(int x, int y, int n);
  11.  
  12. int main() {
  13. int n;
  14. cin >> n;
  15.  
  16. int** board = new int*[n]();
  17. for(int i=0; i<n; i++)
  18. board[i] = new int[n]();
  19.  
  20. int x, y;
  21. cin >> x >> y;
  22.  
  23. board[x][y] = 1;
  24. try2Move(2, x, y, board, n);
  25.  
  26. for(int i=0; i<n; i++)
  27. delete[] board[i];
  28. delete[] board;
  29.  
  30. return 0;
  31. }
  32.  
  33. void printAns(int** board, int n) {
  34. for(int i=0; i<n; i++) {
  35. for(int j=0; j<n; j++) {
  36. cout << board[i][j] << " ";
  37. }
  38. cout<<"\n";
  39. }
  40. }
  41.  
  42. bool isInBoard(int x, int y, int n) {
  43. if(x < 0 || x >= n) return false;
  44. if(y < 0 || y >= n) return false;
  45. return true;
  46. }
  47.  
  48. //===============================================================
  49.  
  50. bool checkAns = false;
  51.  
  52. bool nextCellIsFirstCell(int x, int y, int** board, int n) {
  53. for (int i=0; i<8; i++) {
  54. int xN = x + row[i];
  55. int yN = y + col[i];
  56. if(!isInBoard(xN, yN, n)) continue;
  57.  
  58. if(board[xN][yN] == 1)
  59. return true;
  60. }
  61. return false;
  62. }
  63.  
  64. void try2Move(int count, int x, int y, int** board, int n) {
  65. if(checkAns == true) return;
  66. if(count > n*n) {
  67. if(!nextCellIsFirstCell(x, y, board, n)) return;
  68. printAns(board, n);
  69. checkAns = true;
  70. }
  71.  
  72. for (int i=0; i<8; i++) {
  73. int xN = x + row[i];
  74. int yN = y + col[i];
  75.  
  76. //checking:
  77. // (1) if the next cell is valid
  78. // (2) check if the next cell is visited
  79. if(!isInBoard(xN, yN, n)) continue;
  80. if(board[xN][yN] != 0) continue;
  81.  
  82. board[xN][yN] = count;
  83. try2Move(count+1, xN, yN, board, n);
  84. board[xN][yN] = 0;
  85. }
  86. }
Success #stdin #stdout 0.04s 5300KB
stdin
6
0 0
stdout
1 22 27 30 3 20 
26 31 2 21 8 29 
23 36 25 28 19 4 
32 13 34 7 16 9 
35 24 11 14 5 18 
12 33 6 17 10 15