代码随想录 Leetcode51. N 皇后

题目:

代码随想录 Leetcode51. N 皇后_第1张图片


代码(首刷看解析 2024年2月6日):

class Solution {
private:
    vector> res;
    void backtracking(int n, int row, vector& chessboard) {
        if (row == n) {
            res.push_back(chessboard);
            return;
        }
        for (int col = 0; col < n; ++col) {
            if (isValid(row, col, n, chessboard)) {
                chessboard[row][col] = 'Q';
                backtracking(n, row + 1, chessboard);
                chessboard[row][col] = '.';
            }
        }
        return;
    }
    bool isValid(int row, int col, int n, vector& chessboard) {
        /*检查列*/
        for (int i = 0; i <= row; ++i) {
            if (chessboard[i][col] == 'Q') {
                return false;
            }
        }

        /*检查右上斜角*/
        for (int i = row - 1, j = col + 1; i >=0 && j < n; --i, ++j) {
            if(chessboard[i][j] == 'Q'){
                return false;
            }
        }

        /*检查左上斜角*/
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
            if(chessboard[i][j] == 'Q'){
                return false;
            }
        } 
        return true;
    }
public:
    vector> solveNQueens(int n) {
        vector chessboard(n, string(n, '.'));
        backtracking(n, 0, chessboard);
        return res;
    }
};

你可能感兴趣的:(#,leetcode,---,hard,算法)