8皇后問題的解法執行個體代碼

來源:互聯網
上載者:User

複製代碼 代碼如下:#include <stdio.h>

#define MAX 200
#define Empty 0
#define Full 1
#define N 8

unsigned char qipan[N][N][N]={MAX};//初始化8張棋盤表示每下一步的
void input(int i);
int count = 0;

int main()
{
input(0);
getchar();
return 0;
}
void input(int i)
{
int x=0,y=0;
int p=0,q=0;
int flag = 0;
//初始化當前棋盤
if(i!=0)
{
for(x=0;x<N;x++)
{
for(y=0;y<N;y++)
{
qipan[i][x][y] = qipan[i-1][x][y];
}
}
}
else
{
for(x=0;x<N;x++)
{
for(y=0;y<N;y++)
{
qipan[i][x][y] = MAX;
}
}
}
//遞迴結束
if(i==N)
{
count++;
for(x=0;x<N;x++)
{
for(y=0;y<N;y++)
{
printf("%d ",qipan[i-1][x][y]);
}
printf("\n");
}
printf("%d\n",count);
return;
}

for(y=0;y<N;y++)
{
//找到空位
if(qipan[i][i][y]==MAX)
{
//另其為1
qipan[i][i][y] = 1;
//前後左右上下都置為0
for(p=0;p<N;p++)
{
for(q=0;q<N;q++)
{
if(q==y||p==i||(p-i)==(q-y)||(p-i)==(y-q))
if(qipan[i][p][q] == MAX)
qipan[i][p][q] = 0;
}
}
if(flag != -1)
{
//找下一個
input(i+1);
}
//將棋盤變回本層原樣
for(p=0;p<N;p++)
{
for(q=0;q<N;q++)
{
if(i!=0)
qipan[i][p][q] = qipan[i-1][p][q];
else
qipan[i][p][q] = MAX;
}
}
flag =0;
}
}
//找不到空位結束
return;
}

聯繫我們

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