import java.util.*;


public class Solution {

    private Set<Integer> colSet = new HashSet<>();
    private Set<Integer> posSet = new HashSet<>();
    private Set<Integer> nagSet = new HashSet<>();
    private int res = 0;

    /**
     * 
     * @param n int整型 the n
     * @return int整型
     */
    public int Nqueen (int n) {
        // write code here
        if (n < 1) {
            return 0;
        }
        backTrack(0, n);
        return res;
    }

    private void backTrack(int i, int n) {
        if (i == n) {
            res++;
            return;
        }
        for (int j = 0; j < n; j++) {
            if (colSet.contains(j) || posSet.contains(i - j) || nagSet.contains(i + j)) {
                continue;
            }
            colSet.add(j);
            posSet.add(i - j);
            nagSet.add(i + j);
            backTrack(i + 1, n);
            colSet.remove(j);
            posSet.remove(i - j);
            nagSet.remove(i + j);
        }
    }
}