Leetcode 面试题 08.12. 八皇后

Leetcode 面试题 08.12. 八皇后_第1张图片

回溯

class Solution {
public:
    vector<vector<string>> ans;
    
    bool isvalid(int row, int col, vector<string>& chessboard, int n) {
        // 检查列
        for (int i = 0; i < row; i++) {
            if (chessboard[i][col] == 'Q')  
                return false;
        }
        // 检查45度
        for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 'Q')
                return false;
        }
        // 检查135度
        for (int i = row-1, j = col-1; i >= 0 && j >= 0; i--,j--) {
            if (chessboard[i][j] == 'Q')
                return false;
        }
        return true;
    }
    void dfs(int n, int row, vector<string>& chessboard) {
        if (row == n) {
            ans.push_back(chessboard);
            return;
        }
        for (int col = 0; col < n; col++) {
            if (isvalid(row, col, chessboard, n)) {
                chessboard[row][col] = 'Q';
                dfs(n, row + 1, chessboard);
                chessboard[row][col] = '.';
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<string> chessboard(n, string(n, '.'));
        dfs(n, 0, chessboard);
        return ans;
    }
};

你可能感兴趣的:(数据结构与算法,leetcode,算法,c++)