经典8皇后问题
public class Queen {
int[] cols
;
int ways
;
public void setQueens(int n
){
if(n
<1) return;
cols
= new int[n
];
place(0);
System
.out
.println("一共有"+ways
+"种方法");
}
public void place(int row
){
if(row
== cols
.length
){
ways
++;
show();
return;
}
for (int col
=0;col
<cols
.length
;col
++){
if(judgeQueen(row
,col
)){
cols
[row
]=col
;
place(row
+1);
}
}
}
public boolean judgeQueen(int row
,int col
){
for (int i
=0;i
<row
;i
++){
if (cols
[i
] ==col
) return false;
if(row
-i
== Math
.abs(col
-cols
[i
])) return false;
}
return true;
}
void show(){
for (int row
=0;row
<cols
.length
;row
++){
for (int col
=0;col
<cols
.length
;col
++){
if(cols
[row
]==col
) {
System
.out
.print("1 ");
}else {
System
.out
.print("0 ");
}
}
System
.out
.println();
}
System
.out
.println("------------------");
}
public static void main(String
[] args
) {
new Queen().setQueens(4);
}
}
转载请注明原文地址: https://lol.8miu.com/read-7502.html