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 totalNQueens(int n) { int solutions = 0; vector<int> queue(n, -1); recursiveFun(solutions, queue, n, 0); return solutions; } void recursiveFun(int &solutions, vector<int> &queue, int n, int row) { if (row >= n) { ++solutions; } else { for (int j = 0; j < n; ++j) { if (isValid(queue, row, j)) { queue[row] = j; recursiveFun(solutions, queue, n, row + 1); } } } } bool isValid(vector<int> queue, int r, int c) { if (queue.empty()) return true; for (int i = 0; i < r; ++i) { if (queue[i] == c || abs(i - r) == abs(queue[i] - c)) return false; } return true; } };