51 N皇后

方向数组+回溯

class Solution {
public:
    void set(vector<string> &board, vector<string> &ch, int x, int y, int n) {
        constexpr static int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};
        constexpr static int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};
        int pos = x + y * n;
        board[y][x] = 'Q';
        ch[y][x] = 'Q';
        for (int orien = 0; orien < 8; ++orien) {
            for (int _x = x + dx[orien], _y = y + dy[orien];
                 _x >= 0 && _x < n && _y >= 0 && _y < n; _x += dx[orien], _y += dy[orien])
                if (board[_y][_x] != 'Q')
                    board[_y][_x] = 'Q';
        }
    }

    void solve(vector<vector<string>> &dns, vector<string> ch, vector<string> _ch, int x, int y, int n) {
        if (x != -1) 
            set(ch, _ch, x, y - 1, n);
        if (y == n) {
            dns.push_back(_ch);
            return;
        }
        int pos = y * n;
        for (x = 0; x < n; ++x, ++pos)
            if (ch[y][x] != 'Q')
                solve(dns, ch, _ch, x, y + 1, n);
    }

    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> ans;
        if(n==0)
            return ans;
        string t(n, '.');
        vector<string> _ch(n, t), ch(_ch);
        solve(ans, ch, _ch, -1, 0, n);
        return ans;
    }
};

```

转载于:https://www.cnblogs.com/INnoVationv2/p/10283897.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值