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