第一题,八皇后问题
public class Queen {
private int i,k,flag=0;
private int pointer = 1;//列指示器
int[] cellpos = new int[9];//皇后所在行数
public Queen() {
cellpos[pointer] = 1;
cellpos[2] = 3;
pointer = 3;
clean(2);//给第二列之后的列赋一个初值1,因为默认是0,而我们约定的是从1开始.
while(cellpos[1] <= 8) {
if(cellpos[pointer]>8) {
pointer--;
cellpos[pointer]++;
//清理
clean(pointer);
continue;
}
for(i=cellpos[pointer]; i<=8; i++)
if(canStay(i)) break;
if(i>8) {
pointer--;
cellpos[pointer]++;
clean(pointer);
continue;
}else{
cellpos[pointer] = i;
}
if(pointer==8) {
if(flag<3){
printQueen();//将解打印出来
flag++;
}
pointer--;
cellpos[pointer]++;
clean(pointer);
}else{
pointer++;
}
}
}
private boolean canStay(int ci) {
//行扫描,判断同一行是否有其它皇后.
for(k=1; k<pointer; k++)
if(cellpos[k]==ci) return false;
//对角线扫描,判断对角线上是否有其它皇后.注意有两条对角线.
for(k=1; k<pointer; k++)
if((ci==cellpos[k]+(pointer-k)) ||
(ci==cellpos[k]-(pointer-k)))
return false;
return true;
}
private void clean(int pointer) {
for(k=pointer+1; k<9; k++)
cellpos[k] = 1;
}
private void printQueen() {
for(i=1;i<9;i++){
for(k=1;k<9;k++){
int a=cellpos[k];
if(i==a)
System.out.print("Q"+" ");
else
System.out.print("X"+" ");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
new Queen();
}
}