fork download
  1. #define N 8
  2. #include <iostream>
  3. int board[N][N];
  4. using namespace std;
  5. void printsolution(int board[N][N])
  6. {
  7. for(int i=0; i<N; i++)
  8. {
  9. for(int j=0; j<N; j++)
  10. {
  11. cout<<board[i][j];
  12. }
  13. cout<<endl;
  14. }
  15. }
  16. bool issafe(int board[N][N], int row, int col)
  17. {
  18. int i,j;
  19. for(i=0; i<=N; i++)
  20. {
  21. if(board[i][col])
  22. return false;
  23. }
  24. for(i=row, j=col; j>=0&& i>=0; j--,i--)
  25. {
  26. if(board[i][j])
  27. return false;
  28. }
  29. for(i=row, j=col; i<=N&&j>=0; i++, j--)
  30. {
  31. if(board[i][j])
  32. return false;
  33. }
  34. }
  35. bool solveNQ(int board[N][N], int col)
  36. {
  37. if(col>=N)
  38. return true;
  39. for(int i=0; i<=N; i++)
  40. {
  41. if(issafe(board,i,col))
  42. {
  43. board[i][col]=1;
  44. if(solveNQ(board,col+1))
  45. return true;
  46. board[i][col]=0;
  47. }
  48. }
  49. return false;
  50. }
  51. bool getsol()
  52. {
  53. //board[8][8]={{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0}};
  54. if(solveNQ(board,0)==false)
  55. {
  56. cout<<"Soln de";
  57. return false;
  58. }
  59. printsolution(board);
  60. return true;
  61. }
  62.  
  63. int main() {
  64. // your code goes here
  65. getsol();
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
11111111
00000000
00000000
00000000
00000000
00000000
00000000
00000000