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

52. N-Queens II

时间:2017-05-11 10:17:45      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:ssi   sum   --   dfs   out   vector   png   font   src   

Problem statement:

Follow up for N-Queens problem.

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

技术分享

Solution:

Compare with 51. N-Queens, this problem wants the number of  possible solutions. It also belongs to DFS, however, it belongs to another DFS template.

The return value of DFS function should be an integer instead of void. In each level DFS, the return value should be the sum of lower level result. The return value of final result is the DFS result from 0.

class Solution {
public:
    int totalNQueens(int n) {
        vector<string> solu(n, string(n, 0));
        return NQueens(solu, 0, n, n);
    }
private:
    int NQueens(vector<string>& solu, int row, int col, int n){
        if(row == n){
            return 1;
        }
        int cnt = 0;
        for(int i = 0; i < col; i++){
            if(isvalid(solu, row, i, n)){
                solu[row][i] = Q;
                cnt += NQueens(solu, row + 1, col, n);
                solu[row][i] = .;
            }
        }
        return cnt;
    }
    bool isvalid(vector<string>& solu, int row, int col, int n){
        for(int i = row - 1, left = col - 1, right = col + 1; i >= 0; i--, left--, right++){
            if(solu[i][col] == Q || (left >= 0 && solu[i][left] == Q) || (right < n && solu[i][right] == Q)){
                return false;
            }
        }
        return true;
    }
};        

 

52. N-Queens II

标签:ssi   sum   --   dfs   out   vector   png   font   src   

原文地址:http://www.cnblogs.com/wdw828/p/6839358.html

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