本文主要是介绍leetcode51 N皇后问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://programmercarl.com/0051.N%E7%9A%87%E5%90%8E.html
代码随想录讲的很清楚。
回溯法
- 从上到下按行搜索,因此
back_tracking(chessboard, row + 1)
其参数为row+1 - 判断该位置是否符合
- 终止条件是
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_;}
};
这篇关于leetcode51 N皇后问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!