当前位置:   article > 正文

leetcode51 N皇后问题

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<string> 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_;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/194502?site
推荐阅读
相关标签
  

闽ICP备14008679号