fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define max 10
  4. int arr[max];
  5.  
  6. void display(int n){
  7. for(int i=1;i<=n;i++){
  8. for(int j=1;j<=n;j++){
  9. if(arr[i]!=j)
  10. cout<<"_ ";
  11. else
  12. cout<<"Q ";
  13. }
  14. cout<<endl;
  15. }
  16. cout<<"=++++++++++++++++++++++++++++++++++++++++++++++++"<<endl;
  17. }
  18. bool canplace(int k,int i){
  19. for(int j=1;j<k;j++){
  20. if(arr[j]==i || abs(arr[j]-i)==abs(j-k))
  21. return false;
  22. }
  23. return true;
  24. }
  25. void nQueen(int k,int n){
  26. for(int j=1;j<=n;j++){
  27. if(canplace(k,j)){
  28. arr[k]=j;
  29. if(k==n)
  30. display(n);
  31. else{
  32. nQueen(k+1,n);
  33. }
  34. }
  35. }
  36. }
  37.  
  38. int main(){
  39. int n=4;
  40. nQueen(1,n);
  41. return 0;
  42. }
Success #stdin #stdout 0s 4392KB
stdin
Standard input is empty
stdout
_  Q _  _  
_  _  _  Q 
Q _  _  _  
_  _  Q _  
=++++++++++++++++++++++++++++++++++++++++++++++++
_  _  Q _  
Q _  _  _  
_  _  _  Q 
_  Q _  _  
=++++++++++++++++++++++++++++++++++++++++++++++++