N-queens
TheN-Queens puzzle is the problem of placingNQueens onN×NChessboard such that no two queens attack each other.
Given an integerN, Return all distinct solutions toN-Queens puzzle.
Each solution contains a distinct board configuration ofN-Queens 'placement, where'Q'And'.'Both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-Queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]
This is a routine with Sudoku solver. The Backtracking Method tries all possibilities and saves the feasible solution. You can compare them.
We first use vector <int> to store the feasible solution. The subscript represents the row number, and the element represents the column number.
Therefore, solution 1 is expressed as [1, 3,] using vector <int>.
The problem solving process is to try the number of columns in the next row (0 ~ N-1). If feasible, recursion is performed. If not, the pop-up will continue to try the next column.
A lot of comments are added to the Code, which is easy to understand.
class Solution {public: vector<vector<string> > solveNQueens(int n) { vector<vector<int> > result; //全局变量 vector<int> cur; //递归栈中的变量 solve(result, cur, n); //符合条件的cur加入result return transfer(result, n); //vector<int>转为vector<string> } void solve(vector<vector<int> > &result, vector<int> cur, int n) { if(cur.size() == n) {//找到解 result.push_back(cur); } else { for(int i = 0; i < n; i ++) {//尝试所有可能 cur.push_back(i); if(isValid(cur)) {//可行则递归下去 solve(result, cur, n); } cur.pop_back(); } } } vector<vector<string> > transfer(vector<vector<int> > &result, int n) { vector<vector<string> > ret; for(vector<vector<int> >::size_type st1 = 0; st1 < result.size(); st1 ++) {//第st1个解 vector<string> cur(n, string(n,‘.‘)); for(vector<int>::size_type st2 = 0; st2 < n; st2 ++) {//第st2行 cur[st2][result[st1][st2]] = ‘Q‘; } ret.push_back(cur); } return ret; } bool isValid(vector<int> &cur) {//针对新加点进行验证 int sz = cur.size(); int row = sz-1; //新加点的行数sz-1 int col = cur[sz-1]; //列数cur[sz-1] for(vector<int>::size_type st = 0; st < sz-1; st ++) { //验证同列错误(由于数组下标不同,同行错误不存在) if(col == cur[st]) return false; //验证同对角线错误 if(fabs((double)row-st)==fabs((double)col-cur[st])) return false; } return true; }};
[Leetcode] n-queens