package qinglin.learn.arithmetic;
public class EightQueens_03
{
String position[][]=new String[8][8];
int column[] = new int[8];
int right[]=new int[15];
int reverse[]=new int[15];
final int ROW=8;
final int COLUMN=8;
int sum=0;
public void initPosition(String position[][],int columns,int rows)
{
for(int i=0;i<rows;i++)
for(int j=0;j<columns;j++)
position[i][j]="○";
for(int i=0;i<column.length;i++)
column[i]=0;
for(int i=0;i<right.length;i++)
{
right[i]=0;
reverse[i]=0;
}
}
public void printPosition(int sum,int column,int row)
{
System.out.println(sum);
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
System.out.print(position[i][j]);
System.out.println();
}
}
public void getQueenPositions(int i)
{
for(int icolumn=0;icolumn<ROW;icolumn++)
{
if((column[icolumn]==0)&&(right[i-icolumn+7]==0)&&(reverse[i+icolumn]==0))
{
position[i][icolumn]="●";
column[icolumn]=1;
right[i-icolumn+7]=1;
reverse[i+icolumn]=1;
if(i<7)
getQueenPositions(i+1);
else
{
printPosition(++sum,ROW,COLUMN);
}
position[i][icolumn]="○";
column[icolumn]=0;
right[i-icolumn+7]=0;
reverse[i+icolumn]=0;
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
EightQueens_03 demo = new EightQueens_03();
System.out.println(System.currentTimeMillis());
demo.initPosition(demo.position, demo.ROW, demo.COLUMN);
demo.getQueenPositions(0);
System.out.println(System.currentTimeMillis());
}
}
八皇后问题
最新推荐文章于 2023-07-07 14:04:01 发布