码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] N-Queens II

时间:2015-08-09 10:40:41      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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
};

 

[LeetCode] N-Queens II

标签:

原文地址:http://www.cnblogs.com/vincently/p/4714635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!