leetcode51 N皇后问题

https://programmercarl.com/0051.N%E7%9A%87%E5%90%8E.html
代码随想录讲的很清楚。

回溯法

  1. 从上到下按行搜索,因此back_tracking(chessboard, row + 1)其参数为row+1
  2. 判断该位置是否符合
  3. 终止条件是i==n
class Solution {
public:
    // vector path_;
    vector<vector<string>> res_;
    bool valid(vector<string>& chessboard, int row, int col) {
        for (int j = 0; j < row; j++) {
            if (chessboard[j][col] == 'Q') {
                return false;
            }
        }

        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }

        for (int i = row, j = col; i >= 0 && j < chessboard.size(); i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }

    void back_tracking(vector<string> chessboard, int row) {
        if (row == chessboard.size()) {
            res_.push_back(chessboard);
            return;
        }
        // for (int i = row; i < chessboard.size(); i++) {
        for (int j = 0; j < chessboard[0].size(); j++) {
            if (valid(chessboard, row, j)) {
                chessboard[row][j] = 'Q';
                back_tracking(chessboard, row + 1);
                chessboard[row][j] = '.';
            }
        }
        // }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<string> chessboard(n, string(n, '.'));
        back_tracking(chessboard, 0);
        return res_;
    }
};

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