java求解八皇后的重复问题
先说下我的思路,首先八皇后不能在同一行。所以int[8] 表示每一行皇后所在的列。然后依次递归,比如{1, 3, 5 ,2 ,6 ,8 ,4 ,7 }表示第一行皇后在第一列,第二行在第三列依此类推。
源码如下
public class EightQueen {
static final int ROWS=8;
static final int LINES=8;
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<int[]> result = new ArrayList<int[]>();
selectNextRow(1, 1, null, result);
for (int[] item : result) {
for (int i : item) {
System.out.print(i+" ");
}
System.out.print("\n");
}
}
static void selectNextRow(int row,int line,int[] arry,ArrayList<int[]> arlist)
{
for(int i=1;i<=LINES;i++)
{
if(row==1)
{
int[] ar = new int[8];
ar[row-1]=i;
selectNextRow(row+1, i, ar, arlist);
}
else
{
if(row<=ROWS)
{
int[] temp = new int[8];
temp = arry.clone();
int left=line-1;
int right = line+1;
boolean Inarry = false;
for (int j : temp) {
if(j==i)
{
Inarry=true;
break;
}
}
if(i!=left&&i!=right&&!Inarry)
{
temp[row-1] = i;
selectNextRow(row+1, i, temp, arlist);
if(row==ROWS)
{
arlist.add(temp);
}
}
}
}
}
}
}
最后显示有5242种。知道重复了很多。但是不知道在哪些地方重复了。求大神不吝赐教