递归求N皇后(java)
package dane.queen.com;
/*
* @author dane-zhu
* 递归求N皇后,2011.2.22
*/
public class Queen {
private final static int N = 8;
private static char[][] matrix = new char[N][N];
private static int x;
private static int sum;
public Queen() {
for(int i = 0 ;i < N;i++){
for(int j = 0; j < N;j++){
matrix[i][j] = '*';
}
}
x = 0;
sum = 0;
}
private Boolean check(char[][] m,int x,int y){
for(int i = 0 ;i < N;i++){
for(int j = 0; j < N;j++){
//判断上下左右有没有'Q'
if(m[i][y] == 'Q' || m[x][j] == 'Q')
return false;
//判断上斜线上有没有'Q'
if((i != x && j != y) && ((i - x)/(j - y * 1.0) == 1.0 ||(i - x)/(j - y * 1.0) == -1.0)){
if(m[i][j] == 'Q')
return false;
}
}
}
return true;
}
private void find(char[][] m,int x){
if(x == N){
sum++;
print(m);
return;
}
for(int i = 0;i < N;i++){
if(check(m, x, i) == true){
m[x++][i] = 'Q';
//递归查找
find(m, x);
m[--x][i] = '*';
}
}
return;
}
private void print(char[][] m){
System.out.println("Solve of " + sum);
for(int i = 0 ;i < N;i++){
for(int j = 0; j < N;j++){
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args){
Queen queen = new Queen();
queen.find(matrix, x);
}
}