首页 > 代码库 > 八皇后

八皇后

// 创建并初始化数组    
int [] list = new int [arrSize];
for(int i = 0; i < arrSize; i++)
    list[i] = i;
// 随机打乱数组
public static void randomizeArray(int [] list){
    int arrSize = list.length;
    int ranIndex;
    for(int i = 0; i < arrSize; i++){
        ranIndex = (int)(Math.random() * arrSize);
        if(ranIndex != i){
            int temp = list[i];
            list[i] = list[ranIndex];
            list[ranIndex] = temp;
        }
    }
}

// 6.20 游戏:八皇后
    public void solveEightQueens(){
        int arrSize = 8;
        int [] list = new int [arrSize];
        for(int i = 0; i < arrSize; i++)
            list[i] = i;
        int count = 0;
        boolean notValid = true;
        while(notValid){
            count ++;
            notValid = false;
            randomizeArray(list);

 

            for(int i = 0; i < arrSize; i++){
                for(int j = i + 1; j < arrSize; j++){
                    if(j - i == Math.abs(list[j] - list[i])){  // 检查是否满足条件
                        notValid = true; 
                        break;
                    }
                }
                if(notValid) break;
            }   // end of outer for loop
        }   // end of while

        // print the result
        int i;
        System.out.println("O(∩_∩)O哈哈~, I have tried " + count + " times, and eventually succeed.");
        for(i = 0; i < arrSize - 1; i++){
            System.out.print("(" + i + ", " + list[i] + "), ");
        }
        System.out.println("(" + i + ", " + list[i] + ")");
    }

// 6.22 游戏:多种八皇后问题的解决方案(利用int值递增,然后将其转变为八进制字符串,再进行检查)
    public static void solveEightQueensMethod(){
        int start = 001234567;  // 八进制
        int end = 076543210;   // 八进制
        int count = 0;   // 计算有效的布局数
        for(int i = start; i < end; i++){
            boolean isValid = isValid(i);
            if(isValid){

                if(++count % 7 == 0)
                    System.out.println(Integer.toOctalString(i) + ": " + isValid);
                else System.out.print(Integer.toOctalString(i) + ": " + isValid + "  ");
            }
        }
        System.out.println("count = " + count);  // 输出有效的布局数
    }
// 检查 number 是否是有效布局
    public static boolean isValid(int number){
        String numOct = Integer.toOctalString(number);
        int arrSize = numOct.length();
        if(arrSize==7) { // 如果number第一位是0,则生成的字符串只有七个字符
            numOct = ‘0‘ + numOct;
            arrSize ++;
        }
        for(int i = 1; i < arrSize; i ++){
            for(int j = i - 1; j >= 0; j--){
                if(numOct.charAt(i) == numOct.charAt(j)) return false;   // 同一列
                if(i - j == Math.abs(numOct.charAt(i) - numOct.charAt(j))) return false;  //同一条对角线
            }
        }
        return true;
    }

八皇后