52. N-Queens II

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
 class Solution {
     //public int res = 0;
    public int totalNQueens(int n) {
       // List<List<String>> result = new ArrayList<>();
        int[] C = new int[n]; // C[i]表示第i行皇后所在的列编号
        int[] res = {0};
        //int res = 0;
        dfs(C, 0,res);
        return res[0];
    }
    public  void dfs(int[] C, int row,int[] res) {
        final int N = C.length;
        if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
            res[0]++;
            return;
        }

        for (int j = 0; j < N; ++j) {  // 扩展状态,一列一列的试
            final boolean ok = isValid(C, row, j);
            if (!ok) continue;  // 剪枝,如果非法,继续尝试下一列
            // 执行扩展动作
            C[row] = j;
            dfs(C, row + 1,res);
            // 撤销动作
            // C[row] = -1;
        }
    }

    /**
     * 能否在 (row, col) 位置放一个皇后.
     *
     * @param C 棋局
     * @param row 当前正在处理的行,前面的行都已经放了皇后了
     * @param col 当前列
     * @return 能否放一个皇后
     */
     public boolean isValid(int[] C, int row, int col) {
        for (int i = 0; i < row; ++i) {
            // 在同一列
            if (C[i] == col) return false;
            // 在同一对角线上
            if (Math.abs(i - row) == Math.abs(C[i] - col)) return false;
        }
        return true;
    }
}

把不要的都去掉就可以。

记住int传到method里面是无法修改的,替代的方法有1.设置全局变量,2.用一个长为1的数组代替。

posted @ 2019-09-20 10:10  Schwifty  阅读(110)  评论(0编辑  收藏  举报