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

129_leetcode_N-Queens

2014-07-21 15:48 246 查看
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.."]
]


1:注意特殊情况;2:采用递归的方法,当遍历的时候满足题意,获取此时皇后的摆放位置;3:保存每一行放置皇后的位置;递归+回朔的方法 4:注意当前摆放位置不满足题意的条件

vector<vector<string> > solveNQueens(int n)
{
vector<vector<string> > result;
if( n <= 0 )
{
return result;
}

vector<string> tmpSolve;
vector<int> pos(n, 0);

for(int i = 0; i < n; i++)
{
pos[0] = i;
solveNQueensCore(n, 1, result, pos);
}

return result;
}

void solveNQueensCore(int n, int curIndex, vector<vector<string> > &result, vector<int> &pos)
{
if(curIndex == n)
{
vector<string> tmpResult;
for(int i = 0; i < n; i++)
{
string tmp = "";
for(int j = 0; j < n; j++)
{
if(j == pos[i])
{
tmp.push_back('Q');
}
else
{
tmp.push_back('.');
}
}
tmpResult.push_back(tmp);
}
result.push_back(tmpResult);
return;
}

for(int i = 0; i < n; i++)
{
pos[curIndex] = i;
if(check(pos, curIndex))
{
solveNQueensCore(n, curIndex + 1, result, pos);
}
}
}

bool check(vector<int> &pos, int curIndex)
{
for(int i = 0; i < curIndex; i++)
{
if(pos[i] == pos[curIndex] || pos[i] - pos[curIndex] == i - curIndex || pos[i] - pos[curIndex] == curIndex - i)
{
return false;
}
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息