Compact C++ solution


  • 1
    K
    class Solution {
    private:
        vector<int> rows;
        int results;
        
    public:
        int totalNQueens(int n) {
            rows.resize(n, 0);
            results = 0;
            Backtrack(0, n);
            return results;
        }
        
        bool IsNewQValid(int n) {
            for (int i = 0; i < n; i++) {
                if (rows[i] == rows[n] || n - i == abs(rows[n] - rows[i]))
                    return false;
            }
            return true;
        }
        
        void Backtrack(int n, int N) {
            if (n == N) {
                results++;
                return;
            }
            
            for (int i = 0; i < N; i++) {
                rows[n] = i;
                if (IsNewQValid(n))
                    Backtrack(n+1, N);
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.