Skip to content

Instantly share code, notes, and snippets.

@rohit-nsit08
Created August 31, 2011 14:51
Show Gist options
  • Select an option

  • Save rohit-nsit08/1183731 to your computer and use it in GitHub Desktop.

Select an option

Save rohit-nsit08/1183731 to your computer and use it in GitHub Desktop.
8 queens problem using backtracking
#include<stdio.h>
#include<stdlib.h>
int t[8] = {-1};
int sol = 1;
void printsol()
{
int i,j;
char crossboard[8][8];
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
crossboard[i][j]='_';
}
}
for(i=0;i<8;i++)
{
crossboard[i][t[i]]='q';
}
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
printf("%c ",crossboard[i][j]);
}
printf("\n");
}
}
int empty(int i)
{
int j=0;
while((t[i]!=t[j])&&(abs(t[i]-t[j])!=(i-j))&&j<8)j++;
return i==j?1:0;
}
void queens(int i)
{
for(t[i] = 0;t[i]<8;t[i]++)
{
if(empty(i))
{
if(i==7){
printsol();
printf("\n solution %d\n",sol++);
}
else
queens(i+1);
}
}
}
int main()
{
queens(0);
return 0;
}
@nikhi76

nikhi76 commented Feb 19, 2020

Copy link
Copy Markdown

can you please explain me the code

@neilsf

neilsf commented Oct 28, 2020

Copy link
Copy Markdown

I'm not the author but here is how I read this code:

  • The array t holds in which position a queen stands in each row. For example t[0] = 0 means there's a queen in row 0 col 0.
  • The key function here is empty() which checks if a queen can be placed at a certain position. t[i] != t[j] means they're in the same column, abs(t[i] - t[j]) != (i - j) means they align diagonally. Those are invalid positions.
  • The queens() function tests all positions within a row. If the position is good, it calls itself for the next row. Notice that if the next row fails it will continue with the current row where it left off.

Nice job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment