From d1172b5c2f10f9efdd89b09a284b95a247b679f2 Mon Sep 17 00:00:00 2001 From: bala <13452927+rfgsdhshgfh@user.noreply.gitee.com> Date: Sat, 13 Jan 2024 15:16:19 +0000 Subject: [PATCH] =?UTF-8?q?=E7=94=A8=E9=80=92=E5=BD=92=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E6=B1=82=E8=A7=A3n=E7=9A=87=E5=90=8E=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: bala <13452927+rfgsdhshgfh@user.noreply.gitee.com> --- ...7\345\220\216\351\227\256\351\242\230.cpp" | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 "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" 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 00000000..d8ebc502 --- /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 -- Gitee