[leetcode] 52. N-Queens II 解题报告

59 篇文章 0 订阅
13 篇文章 0 订阅

题目链接:https://leetcode.com/problems/n-queens-ii/

Follow up for N-Queens problem.

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


思路:和N-Queens problem一样,这个不需要打印出棋盘,因此还要更简单一些。点击这里看上题的解题报告

代码如下:

class Solution {
public:
    void DFS(vector<string>& map, int k, int n, int& ans)
    {
        if(k == n) { ans++; return; }
        for(int i = 0, x, y; i < n; i++)
        {
            for(y = 0; y < k; y++)
                if(map[y][i] == 'Q') break;
            if(y != k) continue;
            for(y = k, x = i; y >=0&&x<n; y--, x++)
                if(map[y][x] == 'Q') break;
            if(!(y<0 || x ==n)) continue;
            for(y = k, x = i; y>=0 && x >=0; y--, x--)
                if(map[y][x] == 'Q') break;
            if(!(y<0 || x < 0)) continue;
            map[k][i] = 'Q';
            DFS(map, k+1, n, ans);
            map[k][i] = '.';
        }
    }
    
    int totalNQueens(int n) {
        vector<string> map(n, string(n, '.'));
        int ans = 0;
        DFS(map, 0, n, ans);
        return ans;
    }
};

class Solution {
public:
    void DFS(vector<vector<bool>>& hash, int n, int index, int& sum)
    {
        if(index >= n) { sum++; return; }
        for(int i = 0; i < n; i++)
        {
            if(!hash[0][i+index] && !hash[1][index-i+n] && !hash[2][i])
            {
                hash[0][i+index] = true;
                hash[1][index-i+n] = true;
                hash[2][i] = true;
                DFS(hash, n, index+1, sum);
                hash[0][i+index] = false;
                hash[1][index-i+n] = false;
                hash[2][i] = false;
            }
        }
    }
    int totalNQueens(int n) {
        if(n <= 0)  return 0;
        vector<bool> tem(2*n+1, false);
        vector<vector<bool>> hash(3, tem);
        int sum = 0;
        DFS(hash, n, 0, sum);
        return sum;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值