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

52. N-Queens II (Graph; WFS)

时间:2015-10-06 12:56:18      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

Follow up for N-Queens problem.

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

技术分享

 

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        result.clear();
        string str="";
        for(int i = 0; i<n;i++) str+= ".";
        vector<string> answer(n,str);
        vector<bool> columnFlag(n,false);
        dfs(answer,columnFlag, n, 0);
        return result;
    }
    void dfs(vector<string> &answer, vector<bool> &columnFlag, int n, int depth){
        if(depth == n) 
        {
            result.push_back(answer);
            return;
        }
        
        bool haveAnswer = true;
        for(int i = 0; i < n; i++)
        {
            if(columnFlag[i]) continue; //check column
            
            for (int j = 1; depth-j >= 0 && i-j >= 0; j++) //check upper left diagonal
            {
                if(answer[depth-j][i-j]==Q) 
                {
                    haveAnswer = false;
                    break;
                }
            }
            if(!haveAnswer)
            {
                haveAnswer = true;
                continue;
            }
            
            for (int j = 1; depth-j >= 0 && i+j <= n-1; j++)  //check upper right diagonal
            {
                if(answer[depth-j][i+j]==Q) 
                {
                    haveAnswer = false;
                    break;
                }
            }
            if(!haveAnswer)
            {
                haveAnswer = true;
                continue;
            }
            
            answer[depth][i] = Q;
            columnFlag[i] = true;
            dfs(answer, columnFlag, n, depth+1);
            answer[depth][i] = .;
            columnFlag[i] = false;
        }  
    }
private:
    vector<vector<string>> result;
};

 

52. N-Queens II (Graph; WFS)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4856959.html

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