|
C语言趣味程序百例精解之java实现(98)八皇后问题
public class NQueen{
int count=0;
int x[]=new int[9];
public void print(){
System.out.printf("(%d>>",++count);
for(int i=1;i<=8;i++)
System.out.printf("%3d",x);
System.out.println();
}
public boolean canPlace(int k){
for(int i = 1; i < k; i++){
//判断处于同一列或同一斜线
if(x == x[k] || Math.abs(k-i) ==Math.abs(x[k]-x))
return false;
}
return true;
}
public void queen(int i){ //8皇后的回溯代码
if(i> 8){
print();
return;
}
for(int j = 1; j <= 8; j++){
x = j;//记录所放的列
if(canPlace(i)) queen(i+1);
}
}
public static void main(String args[]){
new NQueen().queen(1);
}
}运行:
C:\java>javac NQueen.java
C:\java>java NQueen
(1>> 1 5 8 6 3 7 2 4
(2>> 1 6 8 3 7 4 2 5
(3>> 1 7 4 6 8 2 5 3
(4>> 1 7 5 8 2 4 6 3
(5>> 2 4 6 8 3 1 7 5
(6>> 2 5 7 1 3 8 6 4
(7>> 2 5 7 4 1 8 6 3
(8>> 2 6 1 7 4 8 3 5
(9>> 2 6 8 3 1 4 7 5
(10>> 2 7 3 6 8 5 1 4
(11>> 2 7 5 8 1 4 6 3
(12>> 2 8 6 1 3 5 7 4
(13>> 3 1 7 5 8 2 4 6
(14>> 3 5 2 8 1 7 4 6
(15>> 3 5 2 8 6 4 7 1
(16>> 3 5 7 1 4 2 8 6
(17>> 3 5 8 4 1 7 2 6
(18>> 3 6 2 5 8 1 7 4
(19>> 3 6 2 7 1 4 8 5
(20>> 3 6 2 7 5 1 8 4
(21>> 3 6 4 1 8 5 7 2
(22>> 3 6 4 2 8 5 7 1
(23>> 3 6 8 1 4 7 5 2
(24>> 3 6 8 1 5 7 2 4
(25>> 3 6 8 2 4 1 7 5
(26>> 3 7 2 8 5 1 4 6
(27>> 3 7 2 8 6 4 1 5
(28>> 3 8 4 7 1 6 2 5
(29>> 4 1 5 8 2 7 3 6
(30>> 4 1 5 8 6 3 7 2
(31>> 4 2 5 8 6 1 3 7
(32>> 4 2 7 3 6 8 1 5
(33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