leetcode.51. N-Queens
2016-05-23 21:15
435 查看
The n-queens puzzle is the problem of placing n queens on an
n×n chessboard such that no two queens attack each other.
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
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
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 {
vector<vector<string> > vvs;
public:
vector<vector<string> > solveNQueens(int n)
{
vector<int> vi(n);
solveNQueens(vi, n, 0);
return vvs;
}
private:
void solveNQueens(vector<int> &vi, int n, int c)
{
if(c == n)
{
vector<string> vs(n, string(n, '.'));
for(int i = 0; i < n; ++ i)
vs[i][vi[i]] = 'Q';
vvs.push_back(vs);
return;
}
for(vi[c] = 0; vi[c] < n; ++ vi[c])
if(safe(vi, n, c))
solveNQueens(vi, n, c + 1);
}
bool safe(vector<int> &vi, int n, int c)
{
for(int i = 0; i < c; ++ i)
if(vi[i] == vi[c] || abs(vi[c] - vi[i]) == abs(c - i))
return false;
return true;
}
};
n×n chessboard such that no two queens attack each other.
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
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 {
vector<vector<string> > vvs;
public:
vector<vector<string> > solveNQueens(int n)
{
vector<int> vi(n);
solveNQueens(vi, n, 0);
return vvs;
}
private:
void solveNQueens(vector<int> &vi, int n, int c)
{
if(c == n)
{
vector<string> vs(n, string(n, '.'));
for(int i = 0; i < n; ++ i)
vs[i][vi[i]] = 'Q';
vvs.push_back(vs);
return;
}
for(vi[c] = 0; vi[c] < n; ++ vi[c])
if(safe(vi, n, c))
solveNQueens(vi, n, c + 1);
}
bool safe(vector<int> &vi, int n, int c)
{
for(int i = 0; i < c; ++ i)
if(vi[i] == vi[c] || abs(vi[c] - vi[i]) == abs(c - i))
return false;
return true;
}
};
相关文章推荐
- UIImage的 stretchableImageWithLeftCapWidth 方法的使用
- 【创建型】Builder模式
- Android UI组件和UI框架
- Bubble sort, Insertion sort, merge sort, quick sort, heap sort
- alpha、hidden、opaque的区别
- Android Studio中Module的build.gradle详解
- Range Sum Query系列(Immutable,Mutable,2D - Immutable)
- StringBuffer 与 StringBuilder
- 95. Unique Binary Search Trees II
- 【Arduino官方教程第零辑】基础部分 1-3 Arduino软件(IDE)
- GitHub的Pull Request
- UI进阶 KVO
- HDU 2604 Queuing
- StringBuilder与StringBuffer比较
- 【Arduino官方教程第零辑】基础部分 1-1 什么是Arduino
- Part part = request.getPart("upfile"); 报错解决方法
- 动态规划——unique-paths-ii
- 山东省第六届ACM大学生程序设计竞赛-Lowest Unique Price(桶排序)
- 可拖动FPS显示框(UGUI)
- 可拖动FPS显示框(UGUI)