The n-queens puzzle is the problem of placing n queens 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.
For example, There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]class Solution {
public:
vector<vector<string>> solveNQueens(int n)
{
//存储最终结果
vector<vector<string> > res;
//定位位置;存储的是列坐标
//数组下标表示行坐标
int loc[100];
//dfs
dfs(res,loc,0,n);
return res;
}
void dfs(vector<vector<string>> &res,int loc[],int pos,int total)
{
if(total==pos)
{
printboard(res,loc,pos);
return;
}
for(int i=0;i<total;i++)
{
loc[pos]=i;
if(isvaild(loc,pos))
{
dfs(res,loc,pos+1,total);
}
}
}
bool isvaild(int loc[],int pos)
{
for(int i=0;i<pos;i++)
if(loc[i]==loc[pos]||abs(loc[i]-loc[pos])==abs(pos-i))
return false;
return true;
}
void printboard(vector<vector<string>> &res,int loc[],int pos)
{
vector<string> tmp;
for(int i=0;i<pos;i++)
{
string ans;
for(int j=0;j<pos;j++)
{
if(loc[i]!=j)
ans+=".";
else
ans+="Q";
}
tmp.push_back(ans);
}
res.push_back(tmp);
}
};
Queen II
变成了统计解的个数的问题:
Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
public:
int totalNQueens(int n) {
int res=0;
if(n<=0) return 0;
int loc[100];
dfs(res,loc,0,n);
return res;
}
void dfs(int& res,int loc[],int pos,int n)
{
if(pos==n)
{
res++;
return ;
}
for(int i=0;i<n;i++)
{
loc[pos]=i;
if(isvaild(loc,pos))
{
dfs(res,loc,pos+1,n);
}
}
}
bool isvaild(int loc[],int pos)
{
for(int i=0;i<pos;i++)
if(loc[i]==loc[pos]||abs(loc[i]-loc[pos])==abs(i-pos))
return false;
return true;
}
};
参考地址:http://blog.csdn.net/u011095253/article/details/9158473