The n-queens puzzle is the problem of placing nqueens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
Input: 4 Output: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
解题思路:
这道题很明显的递归求法了,就是判断放置的位置是否有效这里麻烦了一些,需要遍历之前的所有行(判断同一行,同一列,斜线上的皇后是否有冲突);
class Solution {
public:
vector<vector<string>> solveNQueens(int n)
{
vector<string> cur(n , string(n ,'.')) ;
backtrack(0 , cur) ;
return ans ;
}
void backtrack(int n , vector<string>& cur)
{
if(n == cur.size()) ans.push_back(cur) ;
for(int i = 0 ; i < cur.size() ; i++)
{
if( isvalid(i , n , cur) )
{
cur[n][i] = 'Q' ;
backtrack(n + 1 , cur) ;
cur[n][i] = '.' ;
}
}
}
bool isvalid(int k , int n , vector<string>& cur) //判断放置的位置是否有效
{
for(int i = 0 ; i < n ; i++)
{
if(cur[i][k] == 'Q') return false ;
}
for(int i = n - 1 , j = k - 1 ; i >= 0 && j >= 0 ; --i , --j)
{
if(cur[i][j] == 'Q') return false ;
}
for(int i = n - 1 , j = k + 1 ; i >= 0 && j < cur.size() ; --i , ++ j)
{
if(cur[i][j] == 'Q') return false ;
}
return true ;
}
private:
vector<vector<string>> ans ;
};