您的位置:首页 > 产品设计 > UI/UE

LeetCode OJ-- N-Queens **

2014-07-29 20:55 267 查看
https://oj.leetcode.com/problems/n-queens/

n皇后问题,1皇后有1个解,4皇后2个解,8皇后也有解……

每个皇后不能在同一行上,同一列上,以及同一条45度线上。

可以把皇后所在位置用一维数组表示,比如 2 0 3 1,表示第0个皇后在第0行的第二个位置上……

所以验证条件就是,不能有两个数相等,不能 位置差值 == 值的差值

N皇后问题,使用递归法。

对于一个皇后,它所属于列的所有位置,遍历,找出合理的位置,之后递归下一个皇后

class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> >  ans;
if(n<=0)
return ans;

vector<int> places(n,-1);

placeQueen(0, n, ans, places);

return ans;
}

// col and lines
bool valid(int i, int j, vector<int> &places)
{
for(int p = 0; p<i; p++)
{
if(places[p] == j || abs(i - p) == abs(places[p] - j))
return false;
}
return true;
}

void placeQueen(int i, int n, vector<vector<string> > &ans, vector<int> &places)
{
// one solution
if(i == n)
{
vector<string> ansPiece;
for(int p = 0; p<n; p++)
{
string str;
str.resize(n);
for(int q = 0; q<places[p]; q++)
str[q] = '.';
str[places[p]] = 'Q';
for(int q = places[p] + 1; q < n; q++)
str[q] = '.';
ansPiece.push_back(str);
}
ans.push_back(ansPiece);
}

for(int col = 0; col < n; col++)
{
if(valid(i,col,places))
{
places[i] = col;
placeQueen(i+1,n,ans,places); // next queue, next line
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: