Skip to content

Instantly share code, notes, and snippets.

@wasi0013
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wasi0013/51de298182259de2ec0f to your computer and use it in GitHub Desktop.
Save wasi0013/51de298182259de2ec0f to your computer and use it in GitHub Desktop.
This is a simple 8-Queen puzzle solution written in C++
#include"bits/stdc++.h"
using namespace std;
main(){
int vec[]={0,1,2,3,4,5,6,7},n=8,c=0;
set <int> mset,nset;
set<int>::iterator it;
do{
mset.clear();
nset.clear();
for(int i=0;i<n;i++){
mset.insert(vec[i]+i);
nset.insert(vec[i]-i);
}
if(mset.size()==nset.size() && mset.size()==n){
printf("Solution %d\n--------\n",c++);
for (int i=0;i<n;i++){
for(int j=0;j<vec[i];j++)printf(".");
printf("Q");
for(int k=0;k<n-vec[i]+1;k++)printf(".");
puts("");
}
puts("\n--------\n");
}
}while(next_permutation(vec,vec+n));
}
/**
#equivalent Python code
from itertools import permutations
n = 8
def printer(vec):print ("\n".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + "\n===\n")
cols = range(n)
for vec in permutations(cols):
if n == len(set(vec[i]+i for i in cols)) \
== len(set(vec[i]-i for i in cols)):
printer( vec )
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment