diff --git "a/2224020152/\347\254\254\344\272\224\345\215\225\345\205\203/\347\224\250\351\200\222\345\275\222\346\226\271\346\263\225\346\261\202\350\247\243n\347\232\207\345\220\216\351\227\256\351\242\230.cpp" "b/2224020152/\347\254\254\344\272\224\345\215\225\345\205\203/\347\224\250\351\200\222\345\275\222\346\226\271\346\263\225\346\261\202\350\247\243n\347\232\207\345\220\216\351\227\256\351\242\230.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..d8ebc502c074851c984aec71884bb937ab39c383 --- /dev/null +++ "b/2224020152/\347\254\254\344\272\224\345\215\225\345\205\203/\347\224\250\351\200\222\345\275\222\346\226\271\346\263\225\346\261\202\350\247\243n\347\232\207\345\220\216\351\227\256\351\242\230.cpp" @@ -0,0 +1,49 @@ +#include +#include +#define N 20; +using namespace std; +int q[20]; +int count_1 = 0; + +void dispasolution(int n) { + cout << "第" << ++count_1 << "个解:"; + for (int i = 1; i <= n; ++i) { + cout << "(" << i << "," << q[i] << ") "; + } + cout << endl; +} + +bool place(int i, int j) { + if (i == 1) return true; + int k = 1; + while (k < i) { + if (q[k] == j || (abs(i - k) == abs(j - q[k]))) { + return false; + } + k++; + } + return true; +} + +void queen(int i, int n) { + if (i > n) dispasolution(n); + else { + + for (int j = 1; j <= n; ++j) { + if (place(i, j)) { + q[i] = j; + queen(i + 1, n); + } + } + } +} + +int main() { + int n; + cout << "皇后问题(n<20)n="; + cin >> n; + if (n >= 20) cout << "n值太大,不能求解" << endl; + else cout << n << "皇后问题求解如下:" << endl; + queen(1, n); + return 0; +} \ No newline at end of file