思路:

题目给出的测试数据范围比较小, 使用回溯就可以AC, 搞的我也没有兴趣去研究高效解法了

总结:

刚开始, 本以为用棋盘问题的状态压缩 DP 就可以解决, 但做完 N-queen 才发现多个皇后并不能在同一条斜线上, 状态压缩的解法似乎就不好用了

代码:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int N;
vector<int> pos;
int result;
bool visited[10]; bool attack(const int &row, const int &col) {
for(int i = 0; i < pos.size(); i ++) {
if(abs(pos[i]-col) == abs(i-row))
return true;
}
return false;
}
void dfs(const int &depth) {
if( depth == N) {
result += 1;
}
for(int i = 0; i < N; i ++) {
if(visited[i] == 0 ) {
if( pos.size() > 0 && attack(depth, i))
continue;
visited[i] = 1;
pos.push_back(i);
dfs(depth+1);
pos.pop_back();
visited[i] = 0;
} }
}
int totalNQueens(int n) {
pos.clear();
result=0;
memset(visited, 0, sizeof(visited));
N = n;
dfs(0);
return result;
}
};
int main() {
Solution solution;
int res = solution.totalNQueens(9);
cout << res << endl;
return 0;
}
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int N;
vector<int> pos;
vector<vector<string> > result;
bool visited[10]; bool attack(const int &row, const int &col) {
for(int i = 0; i < pos.size(); i ++) {
if(abs(pos[i]-col) == abs(i-row))
return true;
}
return false;
}
void dfs(const int &depth) {
if( depth == N) {
vector<string> temp;
string str;
for(int i = 0; i < N; i ++) {
str.clear();
for(int j = 0; j < N; j ++) {
if(pos[i] == j)
str.push_back('Q');
else
str.push_back('.');
}
temp.push_back(str);
}
result.push_back(temp);
}
for(int i = 0; i < N; i ++) {
if(visited[i] == 0 ) {
if( pos.size() > 0 && attack(depth, i))
continue;
visited[i] = 1;
pos.push_back(i);
dfs(depth+1);
pos.pop_back();
visited[i] = 0;
} }
}
vector<vector<string> > solveNQueens(int n) {
pos.clear();
result.clear();
memset(visited, 0, sizeof(visited));
N = n;
dfs(0);
return result;
}
};

  

最新文章

  1. Azure底层架构的初步分析
  2. HTML input-file 上传类型控制
  3. How to get http response.
  4. PHP 用html方式输出Excel文件时的数据格式设置
  5. Linux-0.00运行环境搭建【转】
  6. ASP.NET服务器控件OnClientClick事件中Eval()作为js方法的参数的一种写法
  7. 转:implementing cons/car/cdr without explicit storage
  8. Fish’s mission
  9. 遗传算法Matlab源程序
  10. Javaweb---服务器Tomcat配置
  11. Python系列之反射、面向对象
  12. 07 总结ProgressDialog 异步任务
  13. Guava Cache探索及spring项目整合GuavaCache实例
  14. APNs
  15. Connection lost: The server closed the connection
  16. JavaScript异步和单线程
  17. 编辑你的数学公式——markdown中latex的使用
  18. Excel图标布局,图表样式,图标元素
  19. yii框架的部署方法
  20. [翻译] JSAnimatedImagesView

热门文章

  1. Hadoop集群datanode死掉或者secondarynamenode进程消失处理办法
  2. RTX——第17章 定时器组
  3. 通过google浏览器的开发者工具修改cookie值
  4. 一款基于jquery和css3的响应式二级导航菜单
  5. 工厂模式——(Head first设计模式4)
  6. 怎样使GridView中满足某个条件的行可编辑,其余行不可编辑?
  7. Linux 下 tail 命令
  8. 分布式理论(4):Leases 一种解决分布式缓存一致性的高效容错机制(转)
  9. DataTable的AcceptChanges()和RejectChanges()方法
  10. rails局部模板 render