Generally divided into backtracking and full permutation
Fully arranged (recursive)
1#include <iostream>2#include <algorithm>3 4 using namespacestd;5 6Template <size_t n>structArraysizehelper {Char_[n];};7Template <typename T, size_t n> arraysizehelper<n> makearraysizehelper (t (&) [N]);8 #defineArray_size (a) sizeof (Makearraysizehelper (a))9 Ten BOOLValid_permutation (Const int*queen,intlen) One { A BOOLvalid =true; - - for(inti =0; i < Len; ++i) the { - for(intj = i +1; J < Len; ++j) - { - if(Queen[j]-queen[i] = = J-i | | queen[j]-queen[i] = = i-j) + { -valid =false; + } A } at } - - returnvalid; - } - - voidPermutation (int*queen,intLenintIdxint&count) in { - if(idx = =len) to { + if(Valid_permutation (queen, Len)) + +count; - } the Else * { $ for(inti = idx; i < Len; ++i)Panax Notoginseng { - swap (Queen[i], queen[idx]); thePermutation (queen, Len, idx +1, count); + swap (Queen[i], queen[idx]); A } the } + } - $ //Solved by permutation recursion. $ inteightqueen_permutation_recur () - { - intQueen[] = {0,1,2,3,4,5,6,7 }; the intCount =0; - WuyiPermutation (Queen, (int) Array_size (Queen),0, count); the - returncount; Wu } - About intMain () $ { -cout << eightqueen_permutation_recur () <<Endl; - -System"Pause"); A return 0; +}
Backtracking (Recursive)
#include <iostream>#include<algorithm>using namespacestd;template<size_t n>structArraysizehelper {Char_[n];}; Template<typename T, size_t n> arraysizehelper<n> makearraysizehelper (t (&) [N]);#defineArray_size (a) sizeof (Makearraysizehelper (a))BOOLValid_backtracking (Const int*queen,intLen) { for(inti =0; i < Len; ++i) {Const intdiff = ABS (queen[i)-Queen[len]); if(diff = =0|| diff = = len-i)return false; } return true;}voidPlacequeen (int*queen,intLenintIdxint&count) { if(idx = =Len) { ++count; } Else { for(inti =0; i < Len; ++i) {Queen[idx]=i; if(valid_backtracking (Queen, idx)) {Placequeen (Queen, Len, idx+1, Count); } } }}//Solved by backtracking (DFS) recursion.inteightqueen_backtracking_recur () {intqueen[8]; intCount =0; Placequeen (Queen, (int) Array_size (Queen),0, Count); returncount;}intMain () {cout<< eightqueen_backtracking_recur () <<Endl; System ("Pause"); return 0;}
Reference: http://www.cnblogs.com/codingmylife/archive/2012/10/04/2711839.html
8 Solutions to the Queen's problems