# 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.

![](https://assets.leetcode.com/uploads/2018/10/12/8-queens.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.."]
]
```

```java
public class Solution {
    int count = 0;

    public int totalNQueens(int n) {
        boolean[] columnMarker = new boolean[n]; // columns |
        boolean[] d1 = new boolean[2 * n]; // diagonals \
        boolean[] d2 = new boolean[2 * n]; // diagonals /
        backtracking(0, columnMarker, d1, d2, n);
        return count;
    }

    public void backtracking(int row, boolean[] columnMarker, boolean[] d1marker, boolean[] d2marker, int n) {
        if (row == n)
            count++;

        for (int col = 0; col < n; col++) {
            int id1 = col - row + n;
            int id2 = col + row;
            if (columnMarker[col] || d1marker[id1] || d2marker[id2])
                continue;

            columnMarker[col] = true;
            d1marker[id1] = true;
            d2marker[id2] = true;
            backtracking(row + 1, columnMarker, d1marker, d2marker, n);
            columnMarker[col] = false;
            d1marker[id1] = false;
            d2marker[id2] = false;
        }
    }
}
```
