DP:N皇后

public static int test6(int n){
        if (n<1) {
            return -1;
        }
        int[] record = new int[n];
        
        return nQueens(0, record);
    }
    
    public static int nQueens(int i,int[] record) {
        if (record.length==i) {
            return 1;
        }
        int res = 0;
        for (int j = 0; j < record.length; j++) {
            if (isValid(record, i, j)) {
                record[i] = j;
                res+=nQueens(i+1, record);
            }
        }
        return res;
    }
    
    public static boolean isValid(int[] record,int i,int j){
        for (int k = 0; k < i; k++) {
            if (record[k]==j||Math.abs(record[k]-j)==Math.abs(k-i)) {
                return false;
            }
        }
        return true;
    }

你可能感兴趣的:(DP:N皇后)