Advertisement
Guest User

alsldgjgspfsd

a guest
May 27th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<math.h>
  3.  using namespace std;
  4. char a[10][10];
  5. int n;
  6.  
  7. void printmatrix() {
  8.    int i, j;
  9.    printf("\n");
  10.  
  11.    for (i = 0; i < n; i++) {
  12.       for (j = 0; j < n; j++)
  13.          printf("%c\t", a[i][j]);
  14.       printf("\n\n");
  15.    }
  16. }
  17.  
  18. int getmarkedcol(int row) {
  19.    int i;
  20.    for (i = 0; i < n; i++)
  21.       if (a[row][i] == 'Q') {
  22.          return (i);
  23.          break;
  24.       }
  25. }
  26.  
  27. int feasible(int row, int col) {
  28.    int i, tcol;
  29.    for (i = 0; i < n; i++) {
  30.       tcol = getmarkedcol(i);
  31.       if (col == tcol || abs((row-i)) == abs(col - tcol))
  32.          return 0;
  33.    }
  34.    return 1;
  35. }
  36.  
  37. void nqueen(int row) {
  38.    int i, j;
  39.    if (row < n) {
  40.       for (i = 0; i < n; i++) {
  41.          if (feasible(row, i)) {
  42.             a[row][i] = 'Q';
  43.             nqueen(row + 1);
  44.             a[row][i] = '.';
  45.          }
  46.       }
  47.    } else {
  48.       printf("\nThe solution is:- ");
  49.       printmatrix();
  50.    }
  51. }
  52.  
  53. int main() {
  54.    int i, j;
  55.  
  56.    printf("\nEnter the no. of queens:- ");
  57.    scanf("%d", &n);
  58.  
  59.    for (i = 0; i < n; i++)
  60.       for (j = 0; j < n; j++)
  61.          a[i][j] = '.';
  62.  
  63.    nqueen(0);
  64.    return (0);
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement