資料結構-練習 8 八皇后問題

來源:互聯網
上載者:User
文章目錄
  • 八皇后問題是找到8*8裡那個特定的情形,即8個皇后不能互相攻擊,不能同行,不能同列,也不能正反斜對。
八皇后問題是找到8*8裡那個特定的情形,即8個皇后不能互相攻擊,不能同行,不能同列,也不能正反斜對。          此問題是對所有問題依次進行遍曆,查看是否滿足條件。以4*4 為例子。                                                                                                                         用圖形表示如下:憋了半天,沒想到什麼好辦法。研究生了,笨得跟豬一樣。直接暴力法,管他,電腦總得算出來。      採用遞迴,回溯。貼代碼:                                                   
/*Coder e_mail:shenganbeiyang@163.com      QQ    :501968942*/#include"iostream"using namespace std;void GetGoodResolution(int,int);bool IsConfliction(int * ,int );void printQueen(int *);const int N=8;static int count=0;int a[N];//下標表示行數,數組的值表示列數。所以行數一定不相同,我們只要考慮列數就可以了int main(){ GetGoodResolution(0,N); cout<<"總共輸出個數為:"<<count; return 0;}//採用遞迴實現void  GetGoodResolution( int r,int N)//r表示行數{        if(r==N) return;//運行到最後一行了,返回   for(int j=0;j<N;++j)//j是列號{   a[r]=j;if(!IsConfliction(a,r)){                   // a[r]=j; if(r==N-1) {printQueen(a);count++;} GetGoodResolution(  r+1, N);//遞迴調用                                                 }//if(j==N-1&&IsConfliction(a,j))//{ //}    // GetGoodResolution(  r, N);//遞迴調用}}bool IsConfliction(int * a,int len){for(int i=0;i<len;++i){  if(a[i]==a[len]||a[i]-a[len]==len-i||a[len]-a[i]==len-i)      {       return true;   break;      }}return false;}void printQueen(int *a){for(int i=0;i<N;++i)cout<<i<<","<<a[i]<<"   ";cout<<endl;}
測試:     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.