Last active
December 22, 2015 18:39
-
-
Save AnimeshShaw/6514289 to your computer and use it in GitHub Desktop.
N Queens Problem implemented in C using backtracking technique. Here we have considered n=4. Live Preview : http://codepad.org/FO5V9gk4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
char a[10][10]; | |
int n = 4; | |
void printmatrix() { | |
int i, j; | |
printf("\n"); | |
for (i = 0; i < n; i++) { | |
for (j = 0; j < n; j++) | |
printf("%c\t", a[i][j]); | |
printf("\n\n"); | |
} | |
printf("-------------------------------------------\n\n"); | |
} | |
int getmarkedcol(int row) { | |
int i, j; | |
for (i = 0; i < n; i++) | |
if (a[row][i] == 'Q') { | |
return (i); | |
break; | |
} | |
} | |
int probable(int row, int col) { | |
int i, tcol; | |
for (i = 0; i < n; i++) { | |
tcol = getmarkedcol(i); | |
if (col == tcol || abs(row - i) == abs(col - tcol)) | |
return 0; | |
} | |
return 1; | |
} | |
void nqueen(int row) { | |
int i, j; | |
if (row < n) { | |
for (i = 0; i < n; i++) { | |
if (probable(row, i)) { | |
a[row][i] = 'Q'; | |
nqueen(row + 1); | |
a[row][i] = '.'; | |
} | |
} | |
} else { | |
printmatrix(); | |
} | |
} | |
int main() { | |
int i, j; | |
for (i = 0; i < n; i++) | |
for (j = 0; j < n; j++) | |
a[i][j] = '.'; | |
printf("\nThe solution's are:- \n\n"); | |
nqueen(0); | |
return 0; | |
} | |
/* | |
The solution's are:- | |
. Q . . | |
. . . Q | |
Q . . . | |
. . Q . | |
--------------------------------------------------- | |
. . Q . | |
Q . . . | |
. . . Q | |
. Q . . | |
--------------------------------------------------- | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment