Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int max = 4; // 棋盤大小,皇后數
- int queen[20]; // 皇后座標陣列
- int count = 0; // 解答數
- void show()
- {
- for (int i = 0; i < max; i++)
- {
- printf("(%d,%d) ", i, queen[i]);
- }
- printf("\n");
- }
- int check(int n)
- {
- for (int i = 0; i < n; i++)
- {
- // 判斷是否 同行 || 斜對角 有棋子
- if (queen[i] == queen[n] || abs(queen[i] - queen[n]) == (n - i))
- {
- return 1;
- }
- }
- return 0;
- }
- void put(int n)
- {
- for (int i = 0; i < max; i++)
- {
- // 放棋子,座標(n,i)
- queen[n] = i;
- // 檢查該位置是否可擺棋子,為非則不進入,棋子跟著迴圈往下走
- if (!check(n))
- {
- if (n == max - 1)
- {
- // 棋子放完,解答數+1
- count++;
- //顯示擺法
- show();
- }
- else
- {
- // 尋找下一列棋子擺放位置
- put(n + 1);
- }
- }
- }
- }
- int main()
- {
- int n;
- printf("請輸入皇后數:");
- scanf("%d",&n);
- max = n;
- clock_t t1 = clock();
- put(0);
- clock_t t2 = clock();
- printf("\n%d 皇后共有 %d 組解\n", max, count);
- printf("共耗時 %lf 秒\n\n", (t2 - t1) / (double)(CLOCKS_PER_SEC));
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment