死亡8皇后游戏,点我试玩
package com.dai.recursion; public class Queue8 { //定义一个Max,表示多少皇后 int max = 8; static int count = 0; //定义数组array ,保存皇后放置位置的结果 int[] array = new int[max]; public static void main(String[] args) { //测试八皇后是否正确 Queue8 queue8 = new Queue8(); queue8.check(0); System.out.println("总共解法:" + count); } //放置第n个皇后 private void check(int n) { if(n==max) { print(); count ++; return; } //依次放入皇后并判断是否冲突 for(int i=0;i<max;i++) { //先把当前皇后放在该行第一列 array[n] = i; if(judge(n)) {//不冲突,放n+1个皇后 check(n+1); } } } //当放置第n个皇后时,检测该皇后是否和前面有冲突.n为第n个皇后 private boolean judge(int n) { for(int i=0; i<n; i++) { if(array[i] == array[n] || Math.abs(n-i)==Math.abs(array[n]-array[i])) return false; } return true; } //将最后结果摆放位置输出 private void print() { for(int i=0;i<array.length;i++) { System.out.print(array[i] + " "); } System.out.println(); } }