LeetCode——51. N-Queens(C++)
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
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 1:
Input: n = 4
Output: [[“.Q…”,“…Q”,“Q…”,“…Q.”],[“…Q.”,“Q…”,“…Q”,“.Q…”]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1
Output: [[“Q”]]
Constraints:
1 <= n <= 9
解题思路:
N皇后问题,回溯算法,用string太麻烦了,就用int记录每行的皇后所在位置,最后在处理成string。每行所在位置安插前先检查一下是否Valid,Valid才继续往下递归。
代码:
class Solution
{
bool isValid(vector<int>& path, int ind, int c)
{
for (int i = 0; i < ind; i++)
{
if (path[i] == c)return false;
if (abs(path[i] - c) == ind - i)return false;
}
return true;
}
void solver(vector<int>& path, vector<vector<int>>& ans, int ind, int n)
{
if (ind == n)
{
ans.push_back(path);
return;
}
for (int i = 0; i < n; i++)
{
if (isValid(path, ind, i))
{
path.push_back(i);
solver(path, ans, ind + 1, n);
path.pop_back();
}
}
return;
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<int>path;
vector<vector<int>>ans;
solver(path, ans, 0, n);
vector<vector<string>>queenans;
for (int i = 0; i < ans.size(); i++)
{
vector<string>temp;
for (int j = 0; j < n; j++)
{
string tt="";
for (int k = 0; k < ans[i][j]; k++)
tt += '.';
tt += 'Q';
for (int k = ans[i][j] + 1; k < n; k++)
tt += '.';
temp.push_back(tt);
}
queenans.push_back(temp);
}
return queenans;
}
};
submission:
22.10.20
class Solution {
bool isValid(vector<int>& path,int i)
{
for(int j=0;j<path.size();j++)
{
int n=path.size();
if(abs(i-path[j])==abs(n-j))return false;
}
return true;
}
void recursion(vector<int>& path,vector<int>& visited,int ind,int n,int& cnt)
{
if(ind==n)
{
cnt++;
return;
}
for(int i=0;i<n;i++)
{
if(visited[i])continue;
if(!isValid(path,i))continue;
visited[i]=1;
path.push_back(i);
recursion(path,visited,ind+1,n,cnt);
visited[i]=0;
path.pop_back();
}
}
public:
/**
*
* @param n int整型 the n
* @return int整型
*/
int Nqueen(int n) {
// write code here
vector<int>path;
vector<int>visited(n,0);
int cnt=0;
recursion(path,visited,0,n,cnt);
return cnt;
}
};