n后问题迭代, 递归解法...

迭代回溯:

#include #include using namespace std; const int MAX = 100; bool isPosVaild(int res[], int row) { for(int i=1; i 0) { (res[row])++; while(res[row] <= count && !isPosVaild(res, row)) (res[row])++; if(res[row] <= count) { if(row == count) display(res, count); else { row++; res[row] = 0; } } else { res[row] = 0; row--; } } } int main(int argc, char *argv[]) { int queenNum; cout << "please input the queen number: "; cin >> queenNum; int res[MAX]; getQueenPos(res, queenNum); system("PAUSE"); return EXIT_SUCCESS; } 

 

递归回溯:

#include #include using namespace std; const int MAX = 100; bool isPosVaild(int res[], int row) { for(int i=1; i count) display(res, count); else { for(int i=1; i<=count; i++) { res[row] = i; if(isPosVaild(res, row)) queenPos(res, count, row + 1); } } } int main(int argc, char *argv[]) { int queenNum; cout << "please input the queen number: "; cin >> queenNum; int res[MAX]; queenPos(res, queenNum, 1); system("PAUSE"); return EXIT_SUCCESS; } 

你可能感兴趣的:(基本算法)