fork(1) download
  1. //http://w...content-available-to-author-only...s.org/archives/12916
  2.  
  3. #include <stdio.h>
  4. #define N 8
  5.  
  6. int isSafe(int x, int y, int soln[][N])
  7. {
  8. if(x>=0 && x<N && y>=0 && y<N && soln[x][y]==-1){
  9. return 1;
  10. }
  11. return 0;
  12. }
  13.  
  14. int generateMoves(int x, int y, int moveNum, int soln[][N], int xMoves[], int yMoves[])//making move number 'moveNum' from x and y.
  15. {
  16. if(moveNum == N*N){
  17. return 1;
  18. }
  19. else{
  20. int i, nextX, nextY;
  21. for(i=0; i<8; ++i){
  22. nextX = x + xMoves[i];
  23. nextY = y + yMoves[i];
  24.  
  25. if(isSafe(nextX, nextY, soln)){
  26. soln[nextX][nextY] = moveNum;
  27. if( generateMoves(nextX, nextY, moveNum+1, soln, xMoves, yMoves) ){
  28. return 1;
  29. }
  30. else{
  31. soln[nextX][nextY] = -1;
  32. }
  33. }
  34. }
  35. return 0;
  36. }
  37. }
  38.  
  39. void printSoln(int soln[][N])
  40. {
  41. int i, j;
  42. for(i=0; i<N; ++i){
  43. for(j=0; j<N; ++j){
  44. printf("%2d ", soln[i][j]);
  45. }
  46. printf("\n");
  47. }
  48. }
  49.  
  50. void moveKnight()
  51. {
  52. int soln[N][N];
  53. int i, j;
  54. for(i=0; i<N; ++i){
  55. for(j=0; j<N; ++j){
  56. soln[i][j] = -1;
  57. }
  58. }
  59.  
  60. int xMoves[] = {2, 2, 1, 1, -1, -1, -2, -2};
  61. int yMoves[] = {1, -1, -2, 2, -2, 2, -1, 1};
  62.  
  63. soln[0][0] = 0; //making the first move i.e. putting the knight at (0, 0)
  64. if( generateMoves(0, 0, 1, soln, xMoves, yMoves) ){
  65. printSoln(soln);
  66. }
  67. else{
  68. printf("\nNOT POSSIBLE\n");
  69. }
  70. }
  71.  
  72. int main()
  73. {
  74. moveKnight();
  75. return 0;
  76. }
Time limit exceeded #stdin #stdout 5s 2720KB
stdin
Standard input is empty
stdout
Standard output is empty