面試訓練八皇后問題

來源:互聯網
上載者:User

題目:在8×8的國際象棋上擺放八個皇后,使其不能相互攻擊,即任意兩個皇后不得處在同一行、同一列或者同一對角斜線上。中的每個黑色格子表示一個皇后,這就是一種合格擺放方法。請求出總共有多少種擺法。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

思路,當然採用回溯法解決,如果本行有何時的位置,則放,然後進入下一行,否則回溯到上層繼續處理。

           前面打算用棧解決問題,可是遇到大麻煩了,我還用遞迴,這太糊塗了,棧用來消除遞迴的,所以這個思路還要解決。

   下面的思路為網路主流思路,即將列儲存到數組中,回溯解決,每一行

  代碼如下

#include "stdio.h"int multi = 8;int colo[8];int total =0;int isMatch(int col){int i=0;for(i=0;i<col;i++){if(colo[i] == colo[col] || abs(colo[i]-colo[col]) == abs(i -col))return 0;} return 1;}void eightQueue(int col){int i=0;for(i=0;i<multi;i++){colo[col] = i;if(isMatch(col)){if(col == 7){total+=1;}else{eightQueue(col+1);}}}}int main(){int col =0;eightQueue(col);printf("total :%d\n",total);return 0;}

非遞迴實現----------

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.