// NQueens solution in C++ // Note: does not free memory as that is difficult to do // since many subsolutions are shared #include template class list { public: T head; list* tail; list(T hd, list* tl) { head = hd; tail = tl; } ~list() { delete head; delete tail; } }; template list* Cons( T hd, list* tl ) { return new list(hd,tl); } template int len(list* xs) { int n = 0; while(xs != NULL) { n++; xs = xs->tail; } return n; } bool safe( int queen, list* xs ) { list* cur = xs; int diag = 1; while(cur != NULL) { int q = cur->head; if (queen == q || queen == (q+diag) || queen == (q-diag)) { return false; } diag++; cur = cur->tail; } return true; } list*>* append_safe( int k, list* soln, list*>* solns ) { list*>* acc = solns; int n = k; while(n > 0) { if (safe(n,soln)) { acc = Cons(Cons(n,soln),acc); } n--; } return acc; } list*>* extend( int n, list*>* solns ) { list*>* acc = NULL; list*>* cur = solns; while(cur != NULL) { list* soln = cur->head; acc = append_safe(n,soln,acc); cur = cur->tail; } return acc; } list*>* find_solutions( int n ) { int k = 0; list*>* acc = Cons*>(NULL,NULL); while(k < n) { acc = extend(n,acc); k++; } return acc; } int nqueens(int n) { return len(find_solutions(n)); } int main(int argc, char ** argv) { int n = 13; if (argc == 2) { n = atoi(argv[1]); } std::cout << nqueens(n) << "\n"; return 0; }