N-Queens DFS

思路:
典型的DFS。时间复杂度O(N!),空间复杂度O(N)。

map[row] 表示第 i row行的皇后放置的位置。
每一层有n种放置方法,一共有n层。

//N-Queens : dfs
class Solution {
private:
vector<vector<string>> res;

void addSolution(vector<int> &map, int n) {
    vector<string> ans;
    for(int i = 0; i < n; ++i) {
        string row(n, '.');
        row[map[i]] = 'Q';
        ans.push_back(row);
    }
    res.push_back(ans);
}
bool canSet(vector<int> &map, int n, int row, int col) {
    //if(map[row] != 0) //row
    //    return false;
    int tmpcol = 0;
    for(int tmprow = 0; tmprow < row; ++tmprow) {
        tmpcol = map[tmprow];
        if(tmpcol == col) //col
            return false;
        if((tmpcol - col) == (tmprow - row)) //right slant line
            return false;
        if((tmpcol - col) == (row - tmprow)) //left slant line
            return false;
    }
    return true;
}
void nqueensSet(vector<int> &map, int n, int row) {
    for(int i = 0; i < n; ++i) {
        if(canSet(map, n, row, i)) {
            map[row] = i;
            if(row == n-1) {
                addSolution(map, n);
                map[row] = 0;
                return;
            }
            nqueensSet(map, n, row+1);
            map[row] = 0;
        }
    }
}
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<int> map = vector<int>(n, 0);
        //judge and set
        nqueensSet(map, n, 0);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值