c++八皇后
10973 ワード
#include
char Chessboard[8][8];
int QueenPlace(int LocX,int LocY);
int N_Queens(int LocX,int LocY,int Queens)
{
int i,j;
int Result=0;
if(Queens==8)
return 1;
else
if(QueenPlace(LocX,LocY))
{
Chessboard[LocX][LocY]='Q';
for(i=0;i<8;i++)
for(j=0;j<8;j++)
{
Result+=N_Queens(i,j,Queens+1);
if(Result>0)
break;
}
if(Result>0)
return 1;
else
{
Chessboard[LocX][LocY]=' ';
return 0;
}
}
else
return 0;
}
int QueenPlace(int LocX,int LocY)
{
int i,j;
if(Chessboard[LocX][LocY]!=' ')
return 0;
for(j=LocY-1;j>=0;j--)
if(Chessboard[LocX][j]!=' ')
return 0;
for(j=LocY+1;j<8;j++)
if(Chessboard[LocX][j]!=' ')
return 0;
for(i=LocX-1;i>=0;i--)
if(Chessboard[i][LocY]!=' ')
return 0;
for(i=LocX+1;i<8;i++)
if(Chessboard[i][LocY]!=' ')
return 0;
i=LocX-1;
j=LocY-1;
while(i>=0 && j>=0)
if(Chessboard[i--][j--]!=' ')
return 0;
i=LocX+1;
j=LocY-1;
while(i<8 && j>=0)
if(Chessboard[i++][j--]!=' ')
return 0;
i=LocX-1;
j=LocY+1;
while(i>=0 && j<8)
if(Chessboard[i--][j++]!=' ')
return 0;
i=LocX+1;
j=LocY+1;
while(i<8 && j<8)
if(Chessboard[i++][j++]!=' ')
return 0;
return 1;
}
void main()
{
int i,j;
for(i=0;i<8;i++)
for(j=0;j<8;j++)
Chessboard[i][j]=' ';
N_Queens(0,0,0);
printf("the graph of 8 Queens on the chessboard.
");
printf(" 0 1 2 3 4 5 6 7
");
printf(" +---+---+---+---+---+---+---+---+
");
for(i=0;i<8;i++)
{
printf(" %d |",i);
for(j=0;j<8;j++)
printf(" %c |",Chessboard[i][j]);
printf("
+---+---+---+---+---+---+---+---+
");
}
}