Problem

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

clipboard.png

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.."]
]

Solution

class Solution {
    int count = 0;
    public int totalNQueens(int n) {
        boolean[] col = new boolean[n];  // columns   |
        boolean[] d1 = new boolean[2*n]; // diagonals \
        boolean[] d2 = new boolean[2*n]; // diagonals /
        helper(0, col, d1, d2, n);
        return count;
    }
    private void helper(int r, boolean[] col, boolean[] d1, boolean[] d2, int n) {
        if (r == n) count++;
        for (int c = 0; c < n; c++) {
            int id1 = c+n-r;
            int id2 = c+r;
            if (col[c] || d1[id1] || d2[id2]) continue;
            col[c] = true; d1[id1] = true; d2[id2] = true;
            helper(r+1, col, d1, d2, n);
            col[c] = false; d1[id1] = false; d2[id2] = false;
        }
    }
}

linspiration
161 声望53 粉丝