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

迭代回溯:

#include <cstdlib> #include <iostream> using namespace std; const int MAX = 100; bool isPosVaild(int res[], int row) { for(int i=1; i<row; i++) if(res[row] == res[i] || (abs(res[row] - res[i]) == abs(row - i))) return false; return true; } void display(int res[], int count) { static int index = 1; cout << index++ << "th valid pos is: " << endl; for(int i=1; i<=count; i++) cout << res[i] << " "; cout << endl; } void getQueenPos(int res[], int count) { int row = 1; res[row] = 0; while(row > 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 <iostream> #include <cstdlib> using namespace std; const int MAX = 100; bool isPosVaild(int res[], int row) { for(int i=1; i<row; i++) if(res[row] == res[i] || (abs(res[row] - res[i]) == abs(row - i))) return false; return true; } void display(int res[], int count) { static int index = 1; cout << index++ << "th valid pos is: " << endl; for(int i=1; i<=count; i++) cout << res[i] << " "; cout << endl; } void queenPos(int res[], int count, int row) { if(row > 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; } 

你可能感兴趣的:(System,input)