Irlance_Dox

Queens

Apr 2nd, 2019
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int max = 4;  // 棋盤大小,皇后數
  6. int queen[20];  // 皇后座標陣列
  7. int count = 0;  // 解答數
  8.  
  9. void show()
  10. {  
  11.     for (int i = 0; i < max; i++)
  12.     {
  13.         printf("(%d,%d) ", i, queen[i]);
  14.     }
  15.     printf("\n");  
  16. }
  17.  
  18. int check(int n)
  19. {  
  20.     for (int i = 0; i < n; i++)
  21.     {
  22.         // 判斷是否 同行 || 斜對角 有棋子
  23.         if (queen[i] == queen[n] || abs(queen[i] - queen[n]) == (n - i))
  24.         {
  25.             return 1;
  26.         }
  27.     }
  28.     return 0;
  29. }
  30.  
  31. void put(int n)  
  32. {  
  33.     for (int i = 0; i < max; i++)
  34.     {
  35.         // 放棋子,座標(n,i)
  36.         queen[n] = i;
  37.        
  38.         // 檢查該位置是否可擺棋子,為非則不進入,棋子跟著迴圈往下走
  39.         if (!check(n))
  40.         {          
  41.             if (n == max - 1)
  42.             {
  43.                 // 棋子放完,解答數+1
  44.                 count++;
  45.  
  46.                 //顯示擺法
  47.                 show();            
  48.             }
  49.             else
  50.             {
  51.                 // 尋找下一列棋子擺放位置
  52.                 put(n + 1);
  53.             }
  54.         }
  55.     }  
  56. }
  57.  
  58. int main()
  59. {
  60.     int n;
  61.     printf("請輸入皇后數:");
  62.     scanf("%d",&n);
  63.     max = n;
  64.  
  65.     clock_t t1 = clock();
  66.     put(0);
  67.     clock_t t2 = clock();
  68.     printf("\n%d 皇后共有 %d 組解\n", max, count);
  69.     printf("共耗時 %lf 秒\n\n", (t2 - t1) / (double)(CLOCKS_PER_SEC));
  70.  
  71.     system("pause");
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment