Leetcode N-Queens II

本文介绍两种解决N皇后问题的方法:一种通过深度优先搜索生成所有可行解并计数;另一种直接判断解的可行性,利用位操作优化性能。

题意:要求输出N皇后问题的解的个数。

思路:返回解的个数。

class Solution {
public:
    vector<vector<string> > re;
    int l;
    int totalNQueens(int n) {
        l = n;
        string ts;
        vector<string> tes;
        for(int i = 0; i < n; i ++) ts += '.';
        for(int i = 0; i < n; i ++) tes.push_back(ts);
        
        dfs(tes, 0);
        
        return re.size();
    }
    void dfs(vector<string> grid, int s) {
        if(s == l) {
            for(int i = 0; i < l; i ++) {
                for(int j = 0; j < l; j ++) {
                    if(grid[i][j] == 'x') grid[i][j] = '.';
                }
            }
            re.push_back(grid);
            return;
        }
        
        vector<string> mygrid;
        for(int i = 0; i < l; ++ i) {
            mygrid = grid;
            if(mygrid[s][i] == 'x') continue;
            if(mygrid[s][i] == '.') {
                mygrid[s][i] = 'Q';
                for(int j = s + 1; j < l; j ++) mygrid[j][i] = 'x';
                for(int j = i - 1, k = s + 1; j >=0 && k < l; j --, k ++) mygrid[k][j] = 'x';
                for(int j = i + 1, k = s + 1; j < l && k < l; j ++, k ++) mygrid[k][j] = 'x';
                
                
                //for(int it = 0; it < l; it ++) cout << mygrid[it] << endl;
                //cout << endl;
                dfs(mygrid, s + 1);
            }
        }
        
        return;
    }
};


另一种思路是不生成可行解,直接判断是否可行。判断是否可行有O(1)的方法。对于(x, y) 上的某个皇后,满足xi + yi = x + y和 n - xi + yi = x + y的位置都不能放置。

class Solution {
public:
    int count;
    int l;
    int totalNQueens(int n) {
        vector<bool> c1(n, false);
        vector<bool> c2(n * 2, false);
        vector<bool> c3(n * 2, false);
        count = 0;
        l = n;
        
        dfs(n, c1, c2, c3);
        
        return count;
    }
    
    void dfs(int row, vector<bool> c1, vector<bool> c2, vector<bool> c3) {
        if(row == 0) count ++;
        
        for(int i = 0; i < l; ++ i) {
            if(c1[i] || c2[row + i] || c3[l - row + i]) continue;
            else {
                c1[i] = true;
                c2[row + i] = true;
                c3[l - row + i] = true;
                dfs(row - 1, c1, c2, c3);
                c1[i] = false;
                c2[row + i] = false;
                c3[l - row + i] = false;
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值