N皇后摆放-递归疗法

    static int answer = 0;
    static int N = 4;//皇后数
    static int[] queen = new int[N + 1];

    private static void putQueen(int j) {// 第几个皇后
        for (int i = 1; i <= N; i++) {//第几列
            queen[j] = i;// 记录列数
            if (check(j)) {// 检查摆放是否合理
                if (j == N) {// 如果摆放到最后一行,说明可以.然后输出
                    answer += 1;
                    System.out.println("answer = " + answer);
                    for (int s = 1; s < queen.length; s++) {
                        System.out.println("s = " + queen[s]);
                    }
                }
                else {// 没有摆放完,向后继续摆放
                    putQueen(j + 1);
                }
            }
        }
    }

    private static boolean check(int j) {
        for (int i = 1; i < j; i++) {
            if (queen[j] == queen[i] || Math.abs(i - j) == Math.abs(queen[j] - queen[i])) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        putQueen(1);
    }

 

posted @ 2022-05-21 19:06  远启  阅读(19)  评论(0编辑  收藏  举报