leetcode--N-Queens

1.题目描述

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,figure below
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

 

image

2.解法分析

这个是DFS的典型应用,回溯法来解这个题的代码如下:

class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

vector<vector<int> >result;
vector<int> path;

mySolveNQueens(result,path,n);

//构建输出的每一项的模板,节省时间
string line(n,'.');
vector<string>square(n,line);
vector<vector<string> >string_result;

vector<vector<int> >::iterator iter;

for(iter=result.begin();iter!=result.end();++iter)
{
vector<string> temp=square;
for(int i=0;i<n;++i)
{
temp[i][(*iter)[i]]='Q';
}

string_result.push_back(temp);
}

return string_result;
}

//深度搜索,不断回溯
void mySolveNQueens(vector<vector<int> > &result,vector<int> &path,int n)
{
//在当前层遍历
for(int i=0;i<n;++i)
{
//如果当前层的某个位置i和之前的摆放不冲突,则加入该位置
if(!isConflict(path,i))
{
path.push_back(i);
if(path.size()==n)result.push_back(path);//找到一个解,继续
else
mySolveNQueens(result,path,n);//还没到最后一层,继续
path.pop_back();//考虑该层的下一个位置,当然,得先把这个位置抹掉
}
}
}

bool isConflict(vector<int> &path,int loc)
{
for(int i=0;i<path.size();++i)
{
//在同一列或者同一斜线上为冲突
if(path[i]==loc||((path[i]-loc)==(path.size()-i))||(path[i]-loc)==(i-path.size()))return true;
}
return false;
}
};

posted @ 2013-09-18 22:37  曾见绝美的阳光  阅读(315)  评论(0编辑  收藏  举报