Advertisement
islam2366

all possible n-queens

Apr 8th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. #include<stdio.h>
  2. int board[10][10];
  3. int N;
  4. void print()
  5. {
  6. for(int i = 0; i < N; i++) {
  7. for (int j = 0; j < N; j++) {
  8. printf(" %d ", board[i][j]);
  9. }
  10. printf("\n");
  11. }
  12. printf("\n");
  13. }
  14. int isSafe(int row, int col)
  15. {
  16. int i, j;
  17. for(i = 0; i < col; i++)
  18. if (board[row][i])
  19. return 0;
  20. for(i=row, j=col; i>=0 && j>=0; i--, j--)
  21. if (board[i][j])
  22. return 0;
  23. for(i=row, j=col; j>=0 && i<N; i++, j--)
  24. if (board[i][j])
  25. return 0;
  26. return 1;
  27. }
  28. int solve(int col)
  29. {
  30. if(col == N) {
  31. print();
  32. return 1;
  33. }
  34. int res = 0;
  35. for(int i = 0; i < N; i++) {
  36. if(isSafe(i, col)) {
  37. board[i][col] = 1;
  38. res = solve(col + 1) || res;
  39. board[i][col] = 0;
  40. }
  41. }
  42. return res;
  43. }
  44. int main()
  45. {
  46. scanf("%d", &N);
  47. solve(0);
  48. return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement