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

leetcode No51. N-Queens

2016-07-16 16:06 405 查看


Question:

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:


Algorithm:

由鹊巢原理,每一层一定有一个Queen,所以不妨从第一行往下试探,用一个数组cur存放Queen的列标。
首先需要一个判断是否合法的函数isVaild判断是否和之前的Queen冲突,由于是逐行试探,所以不需要判断行号,只需判断列号和斜线。
从第一行往下试探,如果是合法的,继续往下试探,一直到n都是合法的那么就是一个解;试探过程中一旦不合法,停止。

Accepted Code:

class Solution {
vector<vector<string>> res;
public:
vector<vector<string>> solveNQueens(int n) {    //有很多解
vector<int> v(n);
result(v,n,0);
return res;
}
private:
bool isValid (vector<int> &cur,int c)    //cur为记录的列数数组,c为当前行数,cur[c]为当前列数
{
for(int i=0;i<c;i++)   //只需判断列数和斜线
{
if(cur[i]==cur[c]||abs(cur[c]-cur[i])==abs(c-i))
return false;
}
return true;
}

void result(vector<int> &cur,int n,int c)
{
if(c==n)      //因为c是从0开始的,所以c==n时,已经有n个数了
{
vector<string> temp(n,string(n,'.'));
for(int i=0;i<n;i++)
{
temp[i][cur[i]]='Q';
}
res.push_back(temp);
}
for(cur[c]=0;cur[c]<n;cur[c]++)
{
if(isValid(cur,c))
{
cur.push_back(cur[c]);
result(cur,n,c+1);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: