八皇后問題-遞迴和迭代兩種解法

來源:互聯網
上載者:User

問題:

經典的八皇后問題

分析:

遞迴解法直觀易懂,但是迭代法需要想點思路

代碼如下:

/* * eightQueen.cpp * *  Created on: 2012-10-14 *      Author: happier */#include <iostream>using namespace std;#define N 8int sum = 0;int *x = new int[N + 1];bool place(int k){int i;for (i = 1; i < k; i++){if (x[i] == x[k] || abs(i - k) == abs(x[i] - x[k]))//第一個判斷行不能相同,第二個判斷對角線不能相同return false;}return true;}void backtrack2()//迭代回溯{int i;x[1]=0;int k=1;while(k>0){x[k]+=1;//當前列加1的位置開始搜尋while((x[k]<=N) && !place(k))//當前列位置是否滿足條件x[k]+=1;//不滿足條件,繼續搜尋下一個位置if(x[k]<=N)//存在滿足條件的列{if(k==N)//是最後一個皇后,完成搜尋{for(i=1; i<=N; i++)cout<<x[i]<<" ";cout<<endl;sum++;}else//不是,則處理下一個皇后{k++;x[k]=0;}}else//回溯{k--;}}}void backtrack(int t) //遞迴回溯{int i = 0;if (t > N)//遞迴結束返回{for (i = 1; i <= N; i++)cout << x[i] << " ";cout << endl;sum++;}else{for (i = 1; i <= N; i++){x[t] = i;//選擇一個皇后if (place(t))//判斷第t列,第i行放一個皇后是否合法backtrack(t + 1);}}}int main(){backtrack(1);cout << sum << endl;sum = 0;backtrack2();cout << sum << endl;return 0;}

總結:

這裡迭代法沒有用棧去類比,因為理解了其中的含義,可以寫出非遞迴法,但是本質上還是存在回溯的。

參考:http://blog.csdn.net/cxllyg/article/details/8055596

聯繫我們

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