Advertisement
Psycho_Coder

N Queens Problem

Oct 10th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. char a[10][10];
  4. int n = 4;
  5.  
  6. void printmatrix() {
  7.     int i, j;
  8.     printf("\n");
  9.     for (i = 0; i < n; i++) {
  10.         for (j = 0; j < n; j++)
  11.             printf("%c\t", a[i][j]);
  12.         printf("\n\n");
  13.     }
  14.     printf("-------------------------------------------\n\n");
  15. }
  16.  
  17. int getmarkedcol(int row) {
  18.     int i, j;
  19.     for (i = 0; i < n; i++)
  20.         if (a[row][i] == 'Q') {
  21.             return (i);
  22.             break;
  23.         }
  24. }
  25.  
  26. int probable(int row, int col) {
  27.     int i, tcol;
  28.     for (i = 0; i < n; i++) {
  29.         tcol = getmarkedcol(i);
  30.         if (col == tcol || abs(row - i) == abs(col - tcol))
  31.             return 0;
  32.     }
  33.     return 1;
  34. }
  35.  
  36. void nqueen(int row) {
  37.     int i, j;
  38.     if (row < n) {
  39.         for (i = 0; i < n; i++) {
  40.             if (probable(row, i)) {
  41.                 a[row][i] = 'Q';
  42.                 nqueen(row + 1);
  43.                 a[row][i] = '.';
  44.             }
  45.         }
  46.     } else {
  47.         printmatrix();
  48.     }
  49. }
  50.  
  51. int main() {
  52.     int i, j;
  53.     for (i = 0; i < n; i++)
  54.         for (j = 0; j < n; j++)
  55.             a[i][j] = '.';
  56.     printf("\nThe solution's are:- \n\n");
  57.     nqueen(0);
  58.     return 0;
  59. }
  60.  
  61.  
  62. /*
  63.  
  64. The solution's are:-
  65.  
  66.  
  67. .   Q   .   .  
  68.  
  69. .   .   .   Q  
  70.  
  71. Q   .   .   .  
  72.  
  73. .   .   Q   .  
  74.  
  75. ---------------------------------------------------
  76.  
  77.  
  78. .   .   Q   .  
  79.  
  80. Q   .   .   .  
  81.  
  82. .   .   .   Q  
  83.  
  84. .   Q   .   .  
  85.  
  86. ---------------------------------------------------
  87.  
  88.  
  89. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement