今天下午ACM的培训讲了一下八皇后问题。我花了两个小时才大致写了一个可运行版本,方法比较笨,但可以实现求出所有解 。以后再优化。
#include <iostream.h>
//棋盘
int arr[8][8]={{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
bool check(int r,int h)
{
if(h>0)
{
for(int hh=h-1;hh>=0;hh--)//检查之前的每一列
{
if(arr[r][hh]==1)
return false;
}
}
if((h>0)&(r>0))
{
for(int rrr1=r-1,int hhh1=h-1;rrr1>=0,hhh1>=0;rrr1--,hhh1--)//左上斜线
{
if(arr[rrr1][hhh1]==1)
return false;
}
}
if((h>0)&(r<7))
{
for(int rrr2=r+1,int hhh2=h-1;rrr2<=7,hhh2>=0;rrr2++,hhh2--)//左下斜线
{
if(arr[rrr2][hhh2]==1)
return false;
}
}
return true;
}
void display()
{
//显示棋盘
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
for(int r0=0;r0<8;r0++)
{
arr[r0][0]=1;
for(int r1=0;r1<8;r1++)
{
if(check(r1,1))
{
arr[r1][1]=1;
for(int r2=0;r2<8;r2++)
{
if(check(r2,2))
{
arr[r2][2]=1;
for(int r3=0;r3<8;r3++)
{
if(check(r3,3))
{
arr[r3][3]=1;
for(int r4=0;r4<8;r4++)
{
if(check(r4,4))
{
arr[r4][4]=1;
for(int r5=0;r5<8;r5++)
{
if(check(r5,5))
{
arr[r5][5]=1;
for(int r6=0;r6<8;r6++)
{
if(check(r6,6))
{
arr[r6][6]=1;
for(int r7=0;r7<8;r7++)
{
if(check(r7,7))
{
arr[r7][7]=1;
display();
cout<<endl;
}
arr[r7][7]=0;
}
arr[r6][6]=0;
}
}
arr[r5][5]=0;
}
}
arr[r4][4]=0;
}
}
arr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