class EightQueen {
public int count= 0 ;
public void EQ ( int row, int n, int [ ] [ ] chess) {
int [ ] [ ] chess2= chess;
if ( row== chess2. length)
{
count+= 1 ;
System. out. println ( "第" + count+ "种结果:" ) ;
System. out. println ( '\n' ) ;
for ( int i= 0 ; i< row; i++ )
{
for ( int j= 0 ; j< chess2[ 0 ] . length; j++ )
{
System. out. print ( chess2[ i] [ j] + "\t" ) ;
}
System. out. println ( '\n' ) ;
}
System. out. println ( '\n' ) ;
}
else
{
for ( int j= 0 ; j< n; j++ )
{
for ( int temp= row; temp< chess2. length; temp++ )
{
for ( int t= 0 ; t< n; t++ )
{
chess2[ temp] [ t] = 0 ;
}
}
if ( notDanger ( row, j, chess2) )
{
chess2[ row] [ j] = 1 ;
EQ ( row+ 1 , n, chess2) ;
}
}
}
}
public boolean notDanger ( int row, int j, int [ ] [ ] chess ) {
boolean flag1= true ;
boolean flag2= true ;
boolean flag3= true ;
int roww= row;
int jj= j;
while ( roww>= 0 ) {
if ( chess[ roww] [ jj] == 1 ) {
flag1= false ;
break ;
}
roww-- ;
}
roww= row;
jj= j;
while ( roww>= 0 && jj>= 0 ) {
if ( chess[ roww] [ jj] == 1 ) {
flag2= false ;
break ;
}
roww-- ;
jj-- ;
}
roww= row;
jj= j;
while ( roww>= 0 && jj< chess[ 0 ] . length) {
if ( chess[ roww] [ jj] == 1 ) {
flag3= false ;
break ;
}
roww-- ;
jj++ ;
}
if ( flag1&& flag2 && flag3 )
{
return true ;
}
else {
return false ;
}
}
}
public class program {
public static void main ( String[ ] args) {
EightQueen testEightQueen= new EightQueen ( ) ;
int nqueen= 8 ;
int [ ] [ ] chess= new int [ nqueen] [ nqueen] ;
for ( int i= 0 ; i< nqueen; i++ )
{
for ( int j= 0 ; j< nqueen; j++ )
{
chess[ i] [ j] = 0 ;
}
}
testEightQueen. EQ ( 0 , nqueen, chess) ;
System. out. println ( "共有解法:" + testEightQueen. count) ;
}
}