Skip to content

Instantly share code, notes, and snippets.

@corehello
Created March 11, 2017 07:57
Show Gist options
  • Save corehello/abb9803dba2b1915863019dc7c66b06a to your computer and use it in GitHub Desktop.
Save corehello/abb9803dba2b1915863019dc7c66b06a to your computer and use it in GitHub Desktop.
8 queen puzzle solver
#include <stdio.h>
/*
You can define the size of Queens
*/
#define QUEEN 8
int row[QUEEN+1];
int l[2*QUEEN];
int r[2*QUEEN];
int rt[QUEEN+1];
int c=0;
void solve8queen(int level)
{
if (level <= QUEEN)
{
int i = 1;
while(i<=QUEEN)
{
if(row[i]!=1&&l[level+i-1]!=1&&r[QUEEN+i-level]!=1)
{
row[i] = l[level+i-1] = r[QUEEN+i-level] = 1;
rt[level] = i;
solve8queen(level+1);
row[i] = l[level+i-1] = r[QUEEN+i-level] = 0;
}
i++;
}
}
else
{
c++;
int i;
for(i = 1; i<=QUEEN; i++)
{
printf("\t%d", rt[i]);
}
printf("\n");
}
}
int
main(int ac, char *av[])
{
solve8queen(1);
printf("totally: %d solutions\n", c);
return 0;
}
@corehello
Copy link
Author

This is for n queen:

#include <stdio.h>
#include <stdlib.h>

void solve8queen(int level, int n,int *row, int *l, int *r, int *c)
{
    if (level <= n)
    {
        int i = 1;
        while(i<=n)
        {
            if(row[i]!=1&&l[level+i-1]!=1&&r[n+i-level]!=1)
            {
                row[i] = l[level+i-1] = r[n+i-level] = 1;
                solve8queen(level+1, n,row,l,r,c);
                row[i] = l[level+i-1] = r[n+i-level] = 0;
            }
            i++;
        }
    }
    else
    {
        (*c)++;
    }
}
int totalNQueens(int n) {
    int row[n+1];
    int l[2*n];
    int r[2*n];
    int c=0;
    solve8queen(1,n,row,l,r,&c);
    return c;
}

int
main(int ac, char *av[])
{
  printf("totally: %d solutions\n", totalNQueens(atoi(av[1])));
  return 0;
}

@corehello
Copy link
Author

Actually, we can use bit to represent the row, l, r, rt, but it is not straightforward. Bit operations are always cool techs.

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