八皇后問題求解1

來源:互聯網
上載者:User

#include <iostream.h>
using namespace std;
int col[8],Left[15],Right[15];
int queen[8];
int n=0;
int sum=0;

void generate()
{
        int h,i;
        for(h=0;h<=7;h++)
        {
                if(col[h]&& Left[n+h] && Right[n-h+7])
                {
                        queen[n]=h;
                        col[h]=false;
                        Left[n+h]=false;
                        Right[n-h+7]=false;
                        n+=1;
                        if(n==8)
                        {
                                sum++;
                                cout<<"  "<<sum;
                                for(i=0;i<=7;i++)
                                cout<<"/t"<<queen[i];
                                cout<<endl;
                        }
                        else generate();
                        n--;
                        Left[n+h]=true;
                        Right[n-h+7]=true;
                        col[h]=true;
                }
        }
}
int  main()
{
        int c,s;
        for(c=0;c<=7;++c)
                col[c]=true;
        for(s=0;s<=14;++s)
        {
                Left[s]=true;
                Right[s]=true;

        }

        cout<<"    行數/t0/t1/t2/t3/t4/t5/t6/t7"<<endl;

        generate();

        cout<<"八皇后擺法總數:"<<sum<<endl;

        return 0;

}

Left[]用來判斷左對角線能否放皇后

Right[]....

h列號

n為行號

 

 

 

 

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int n=8;
int x[8]={0};
int sum=0;

int place(int k)
{
 int j;
 for(j=0;j<k;j++)
  if((fabs(k-j)==fabs(x[j]-x[k]))||(x[j]==x[k])) return 0;
 return 1;
}

void backtrace(int t)
{
 int i;
 if(t>=n)
 {
  putchar('/n');
  for(i=0;i<n;i++)
   printf("%d/t",x[i]);
  sum++;
  if(!(sum%25)) getchar();
 }
 else
  for(i=0;i<n;i++)
  {
   x[t]=i;
   if(place(t)) backtrace(t+1);
  }
}

void main()
{
 backtrace(0);
 printf("%d/n",sum);
 getchar();
}

聯繫我們

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