package com.example.queen;
public class queen_firing {
static int n=0;
//设置棋盘大小
static int Size=8;
public static void initialization(Integer[][] checkerboard){
//创建空的棋盘
for(int i=0;i<Size;i++){
Integer[] integers = new Integer[Size];
for(int j=0;j<Size;j++){
integers[j]=0;
}
checkerboard[i] = integers;
}
}
//放置皇后
private static void asd(int m, int n, Integer[][] checkerboard){
for (int i =0;i<Size;i++){
checkerboard[m][i]=1;
}
for (int i =0;i<Size;i++){
checkerboard[i][n]=1;
}
for (int i =m+1,j=n+1;i<Size&&j<Size;i++,j++){
checkerboard[i][j]=1;
}
for (int i =m+1,j=n-1;i<Size&&j>=0;i++,j--){
checkerboard[i][j]=1;
}
checkerboard[m][n]=9;
}
static void queen_place(Integer[][] checkerboard_liu, int n){
for (int i=0;i<Size;i++){
Integer[][] checkerboard = new Integer[Size][Size];
Apollo(checkerboard,checkerboard_liu);
Integer integer = checkerboard[n][i];
if (integer==0){
asd(n,i,checkerboard);
if (n<Size-1){
queen_place(checkerboard,n+1);
}else {
push(checkerboard);
}
}
}
}
//开始放置
public static void first_queen(){
Integer[][] checkerboard_liu =new Integer[Size][Size];
initialization(checkerboard_liu);
queen_place(checkerboard_liu,0);
}
//复制数组
static void Apollo(Integer[][] b, Integer[][] c1){
for (int i=0;i<Size;i++){
for (int j=0;j<Size;j++){
b[i][j]=c1[i][j];
}
}
}
//打印布局
public static void push(Integer[][] checkerboard){
for (Integer[] integers:checkerboard){
for (Integer integer:integers){
if (integer==1){
System.out.print("*"+" ");
}else {
System.out.print("Q"+" ");
}
}
System.out.println();
}
n++;
System.out.println("----------------------(第"+n+"种布局)");
}
public static void main(String[] args) {
first_queen();
}
}
本代码可以自定义棋盘大小,12格棋盘12个皇后运行八秒,八格以下200毫秒以内。