• Source
    1. /*
    2. ****************************************
    3. Problem: N Queen Problem
    4. ****************************************
    5. Ashis Kumar Chanda
    6. ID: 1624
    7. CSE, DU
    8. ****************************************
    9. ****************************************
    10. */
    11. #include<stdio.h>
    12. #include<math.h>
    13. #include<stdlib.h>
    14. #include <iostream>
    15.  
    16. using namespace std;
    17.  
    18. int n=8; // number of chessboard n*n
    19. int x[9]={0}; // take ans of each row
    20.  
    21. void Nqueen(int k);
    22. bool Can_Place(int a, int k);
    23. void Print_ans();
    24.  
    25. int main()
    26. {
    27. Nqueen(1); // Let, chess board start from (1,1) not (0,0)
    28. Print_ans();
    29. return 0;
    30. }
    31.  
    32. void Nqueen(int k)
    33. {
    34. int i,j;
    35.  
    36. for(j=1; j<= n; j++){
    37. if( Can_Place(j,k) ){
    38. x[k]= j;
    39. if( k== n)
    40. break;
    41.  
    42. Nqueen( ++k);//increment coloumn
    43. }
    44. }
    45. }// end of NQueen
    46.  
    47. bool Can_Place(int a, int k)
    48. {
    49. int j;
    50. for(j=1; j<=(k-1) ; j++){
    51. if( x[j]== a)
    52. return false;// two in same row
    53. }
    54. if(j!=1 )
    55. j--;
    56.  
    57. if( abs(x[j]-a) == abs( j-k ) )
    58. return false; // two in same diagonal
    59.  
    60. return true;// no need to check two in same coloumn
    61. }
    62.  
    63. void Print_ans()
    64. {
    65. puts("Answer is given below:");
    66. for( int i=1; i<=n; i++)
    67. printf(" row %d => coloumn %d\n", x[i], i);
    68. }
    69.