zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    和至少为 K 的最短子数组
    使用VS code编写C++无法实时检测代码的解决办法
    anaconda安装VSCODE后,python报错
    神经网络中sigmod函数和tanh函数的区别
    获取本机IP
    windows C++捕获CMD命令输出
    windows下面生成 dump
    windows 控制台命令输出 捕获
    不使用PEM 文件建立SSL通道
    OpenSSL socket 服务端
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10283905.html
Copyright © 2011-2022 走看看