[LeetCode] N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

 

思路:与http://www.cnblogs.com/vincently/p/4714230.html思路相同。

 

class Solution {
public:
    int result;
    int queen_num_;
    int totalNQueens(int n) {
        result = 0;
        vector<int> a(n, -1);
        queen_num_ = n;
        solveNQueens(a);
        
        return result;
    }
    
    bool IsValid(const vector<int>& a, int row, int col) {
        for (int i = 0; i < row; i++) {
            if (col == a[i] || abs(i - row) == abs(a[i] - col))
                return false;
        }

        return true;
    }

    void solveNQueens(vector<int>& a) {
        int i = 0, j = 0;
        while (i < queen_num_) {
            while (j < queen_num_) {
                if (IsValid(a, i, j)) {
                    a[i] = j;
                    j = 0;
                    break;
                } else {
                    j++;
                }
            }

            if (a[i] == -1) {
                if (i == 0) {
                    return;
                } else {
                    i--;
                    j = a[i] + 1;
                    a[i] = -1;
                    continue;
                }
            }

            if (i == queen_num_  - 1) {
                result++; 
                j = a[i] + 1;
                a[i] = -1;
                continue;
            }
         i++;
        }//while (i < queen_num_);
    }//solveNQueens
};

 

posted @ 2015-08-09 10:00  vincently  阅读(157)  评论(0编辑  收藏  举报