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;
    }
posted @ 2020-02-11 19:05  littledy  阅读(79)  评论(0)    收藏  举报