52. N-Queens II

Solution (C++):

public:
    int totalNQueens(int n) {
        int count = 0;
        vector<string> ans(n, string(n, '.'));
        solveNQueens(ans, 0, n, count);
        
        return count;
    }
private:
    void solveNQueens(vector<string> &ans, int row, int n, int &count) {
        if (row == n)  {
            count++;
            return;
        }
        
        for (int col = 0; col < n; ++col) {
            if (isValid(ans, row, col, n)) {
                ans[row][col] = 'Q';
                solveNQueens(ans, row+1, n, count);
                ans[row][col] = '.';
            }
        }
    }
    bool isValid(vector<string> ans, int row, int col, int n) {
        for (int i = 0; i < row; ++i) {             //判断列是否有'Q'
            if (ans[i][col] == 'Q')  return false;
        }
        for (int i = row-1, j = col-1; i >= 0 && j >= 0; --i, --j) {             //判断45°方向是否有'Q'
            if (ans[i][j] == 'Q')  return false;
        }
        for (int i = row-1, j = col+1; i >= 0 && j <= n-1; --i, ++j) {           //判断135°方向是否有'Q'
            if (ans[i][j] == 'Q')  return false;
        }
        return true;
    }
相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12296296.html