1. 程式人生 > 其它 >[考試總結]ZROI-21-NOIP衝刺-TEST2 總結

[考試總結]ZROI-21-NOIP衝刺-TEST2 總結

連結
N皇后問題是指在N*N的棋盤上要擺N個皇后,要求任何兩個皇后不同行,不同列也不再同一條斜線上,求給一個整數n,返回n皇后的擺法。

import java.util.Scanner;

public class Main {

    private static int doJob(int limit, int rowLimit, int leftLimit, int rightLimit) {
        if (rowLimit == limit) {
            return 1;
        }
        
        int allow = limit & (~(rowLimit | leftLimit | rightLimit));

        int ret = 0;
        while (allow > 0) {
            int lowbit = allow & (-allow);
            ret += doJob(limit, rowLimit | lowbit, (leftLimit | lowbit) << 1, (rightLimit | lowbit) >> 1);
            allow -= lowbit;
        }

        return ret;
    }

    private static int solve(int n) {
        return doJob((1 << n) - 1, 0, 0, 0);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            System.out.println(solve(n));
        }
    }
}
心之所向,素履以往 生如逆旅,一葦以航