• 52 N皇后 II


    class Solution {
    public:
        void print_board(const vector<string> &ch) {
            int _pos = 0;
            cout << "棋盘:" << endl;
            for (const auto &x:ch)
                cout << "  " << x << endl;
        }
    
        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};
            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 reset(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};
            board[y][x] = '.';
            ch[y][x] = '.';
            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] != '.')
                        board[_y][_x] = '.';
            }
        }
    
        void solve(int &ans, vector<string> ch, vector<string> _ch, int x, int y, int n) {
            if (y == n) {
                ++ans;
                return;
            }
            for (; x < n; ++x)
                if (ch[y][x] != 'Q') {
                    set(ch, _ch, x, y, n);
                    solve(ans, ch, _ch, x + 1, y + 1, n);
                    reset(ch, _ch, x, y, n);
                }
        }
    
        int totalNQueens(int n) {
            int ans = 0;
            string t(n, '.');
            vector<string> _ch(n, t), ch(_ch);
    //        for (auto &x:ch)
    //            cout << x << endl;
            solve(ans, ch, _ch, 0, 0, n);
            cout << ans;
            return ans;
        }
    };
    
  • 相关阅读:
    L1和L2正则
    Python基础(一)
    消息分发
    StringList 自定义快速排序
    Delphi Length函数
    接口的委托实现(通过接口)
    接口委托实现--通过类的对象
    排序
    Socket编程(摘抄)
    Delphi线程同步
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10283905.html
Copyright © 2020-2023  润新知