首页 > 其他 > 详细

LeetCode52. N皇后 II

时间:2020-07-06 01:20:26      阅读:67      评论:0      收藏:0      [点我收藏+]

技术分享图片

这题和LeetCode第51题做法一样,只不过不是记录具体方案,而是个数。分析见第51题。

代码如下:

class Solution {
int res = 0;
int n;
vector<string> path;
vector<bool> cols, diagram, anti_diagram;
public:
    int totalNQueens(int _n) {
        n = _n;
        path = vector<string>(n, string(n, ‘.‘));
        cols = vector<bool>(n);
        diagram = anti_diagram = vector<bool>(2 * n);
        DFS(0);
        return res;
    }
    void DFS(int curRow) {
        if(curRow == n) {
            ++res;
            return ;
        }
        for(int i = 0; i < n; ++i) {
            if(cols[i] == false && diagram[curRow - i + n] == false && anti_diagram[curRow + i] == false) {
                cols[i] = diagram[curRow - i + n] = anti_diagram[curRow + i] = true;
                path[curRow][i] = ‘Q‘;
                DFS(curRow + 1);
                path[curRow][i] = ‘.‘;
                cols[i] = diagram[curRow - i + n] = anti_diagram[curRow + i] = false;
            }
        }
    }
};

LeetCode52. N皇后 II

原文:https://www.cnblogs.com/linrj/p/13252568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!