fork download
  1. #include <stdio.h>
  2.  
  3. int isSafe(int k,int i,int *x)
  4. {
  5. int j;
  6. for(j=0;j<k;j++)
  7. {
  8. //old queen is placed at jth row of x[j] column
  9. //new queen to be placed at kth row of ith column
  10. if(i==x[j] || abs(k-j)==abs(i-x[j]))
  11. return 0;
  12. }
  13. return 1;
  14. }
  15.  
  16. void printSol(int* sol, int N)
  17. {
  18. int row;
  19.  
  20. for( row = 0; row < N; ++row )
  21. printf("%d ",sol[row]);
  22. }
  23.  
  24. int Nqueen(int k, int* sol, int N)
  25. {
  26. int col;
  27. if( k == N )
  28. {
  29. printSol(sol,N);
  30. return 1;
  31. }
  32. else
  33. {
  34. for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
  35. {
  36. if( isSafe(k,col,sol) )
  37. {
  38. sol[k] = col;
  39. if( Nqueen(k+1, sol, N) )
  40. return 1;
  41. // sol[k] = 0;
  42. }
  43. }
  44. return 0;
  45. }
  46. }
  47.  
  48. int main()
  49. {
  50. int sol[8], N = 8;
  51. Nqueen(0,sol,N);
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 1720KB
stdin
Standard input is empty
stdout
1 5 8 6 3 7 2 4