51. N-Queens 回溯算法浅谈
2016-04-01 14:59
513 查看
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
代码分析:
这题更是典型的回溯算法,主要是加了一个向量用来存各个位置。不管怎样我都觉得回溯算法很神奇。
代码如下:
static int x[1000];
class Solution {
private:
bool Place(int k)
{
for(int i=0;i<k;++i)
{if((abs(i-k)==abs(x[i]-x[k]))||(x[i]==x[k])) return false;}
return true;
}
void Backtrack(int t,int n,vector<string>q,vector< vector<string>>& v1,string s){
if(t==n)
{v1.push_back(q);}
else
{
for(int i=0;i<n;++i)
{
string s1=s;
s1[i]='Q';
q.push_back(s1);
x[t]=i;
if(Place(t)) Backtrack(t+1,n,q,v1,s);
q.pop_back();
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector< vector<string>> v1;
vector<string> q;
string s(n,'.');
for(int i=0;i<n;++i)
{
x[0]=i;
string s1=s;
s1[i]='Q';
q.push_back(s1);
Backtrack(1,n,q,v1,s);
q.pop_back();
}
return v1;
}
};
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.
代码分析:
这题更是典型的回溯算法,主要是加了一个向量用来存各个位置。不管怎样我都觉得回溯算法很神奇。
代码如下:
static int x[1000];
class Solution {
private:
bool Place(int k)
{
for(int i=0;i<k;++i)
{if((abs(i-k)==abs(x[i]-x[k]))||(x[i]==x[k])) return false;}
return true;
}
void Backtrack(int t,int n,vector<string>q,vector< vector<string>>& v1,string s){
if(t==n)
{v1.push_back(q);}
else
{
for(int i=0;i<n;++i)
{
string s1=s;
s1[i]='Q';
q.push_back(s1);
x[t]=i;
if(Place(t)) Backtrack(t+1,n,q,v1,s);
q.pop_back();
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector< vector<string>> v1;
vector<string> q;
string s(n,'.');
for(int i=0;i<n;++i)
{
x[0]=i;
string s1=s;
s1[i]='Q';
q.push_back(s1);
Backtrack(1,n,q,v1,s);
q.pop_back();
}
return v1;
}
};
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例