首页 > 代码库 > 八皇后—Java
八皇后—Java
package queen;
public class queen {
static boolean col[] = new boolean[8];
static boolean main_diagonal[] = new boolean[15];
static boolean counter_diagonal[] = new boolean[15];
static int record[]=new int[8];
static int count = 0;
public static void search(int x) {
for (int i = 0; i < 8; i++) {
if (col[i] == false && main_diagonal[i - x + 7] == false && counter_diagonal[i + x] == false) {//这里的判断条件是列可用,主对角线可用,次对角线可用
record[x]=i;//记录当前列号
if (x == 7) {//当最后一个安全位置被确定之后,进行计数并画出图像
count++;
for (int k = 0; k < 8; k++) {
for(int j=0;j<8;j++){
if (j==record[k]) {
System.out.print("Q");
}
else System.out.print("*");
}
System.out.println("");
}
System.out.println("\n");
return;//这里的return尤为重要
}
col[i] = true;
main_diagonal[i - x + 7] = true;
counter_diagonal[i + x] = true;
search(x + 1);//递归至下一层
col[i] = false;//回溯时需要解标记
main_diagonal[i - x + 7] = false;
counter_diagonal[i + x] = false;
}
else//如果当前位置不安全,继续向本行下一个位置遍历
continue;
}
}
public static void main(String[] args) {
search(0);
System.out.println("共有"+count+"解法");
}
}
八皇后—Java