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

LeetCode N-Queens

时间:2014-07-16 12:09:34      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   io   div   

class Solution {
private:
    int queen_num;
    vector<vector<string> > res;
public:
    vector<vector<string> > solveNQueens(int n) {
        res.clear();
        queen_num = n;
        
        vector<bool> h(n, false);
        vector<bool> v(n, false);
        vector<bool> lx(n * 2 + 1, false);
        vector<bool> rx(n * 2 + 1, false);

        vector<int> solution;
        
        dfs(solution, h, v, lx, rx);
        
        return res;
    }

    void dfs(vector<int> &mem, vector<bool> &h, vector<bool> &v, vector<bool> &lx, vector<bool> &rx) {
        if (mem.size() == queen_num) {
            add_solution(mem);
            return;
        }
        int row = mem.size();
        int col = 0;
        while (col < queen_num) {
            if (!h[row] && !v[col] && !lx[row + col] && !rx[row + queen_num - col - 1]) {
                h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = true;
                mem.push_back(col);
                dfs(mem, h, v, lx, rx);
                mem.pop_back();
                h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = false;
            }
            col++;
        }
    }

    void add_solution(vector<int> &solution) {
        res.push_back(vector<string>());

        string line(queen_num, .);
        for (int i=0; i<queen_num; i++) {
            line[solution[i]] = Q;
            res.back().push_back(line);
            line[solution[i]] = .;
        }
    }
};

LeetCode N-Queens,布布扣,bubuko.com

LeetCode N-Queens

标签:style   blog   color   for   io   div   

原文地址:http://www.cnblogs.com/lailailai/p/3848045.html

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