[資料結構] N皇后問題

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   sp   for   資料   div   

代碼:

#include <iostream>#include <string.h>#include <algorithm>using namespace std;const int N=100;int c[N];//皇后第i行放在第幾列上int n,total;int cc;//方法數void dfs(int cur){    if(cur>n)    {        cout<<"第"<<cc++<<"種方法:"<<endl<<endl;        for(int i=1;i<=n;i++)        {            cout<<"第 "<<i<<" 個皇后放在第 "<<i<<" 行的第 "<<c[i]<<" 列上"<<endl<<endl;        }        total++;        return;    }    for(int i=1;i<=n;i++)    {        c[cur]=i;        int ok=1;        for(int j=1;j<cur;j++)        {            if(c[cur]==c[j]||cur-c[cur]==j-c[j]||cur+c[cur]==j+c[j])            {                ok=0;                break;            }        }        if(ok)            dfs(cur+1);    }}int main(){    while(1)    {        cout<<"請輸入皇后的個數: "<<endl;        cin>>n;        if(n<=0)        {            cout<<"輸入不合法,程式退出!"<<endl;            break;        }        cc=1;        total=0;        dfs(1);        cout<<"總計有"<<total<<"個解"<<endl<<endl;    }    return 0;}

執行:



[資料結構] N皇后問題

聯繫我們

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