Leetcode: n-queen, n-queen II
2024-10-19 02:19:31
思路:
题目给出的测试数据范围比较小, 使用回溯就可以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;
}
};
最新文章
- Azure底层架构的初步分析
- HTML input-file 上传类型控制
- How to get http response.
- PHP 用html方式输出Excel文件时的数据格式设置
- Linux-0.00运行环境搭建【转】
- ASP.NET服务器控件OnClientClick事件中Eval()作为js方法的参数的一种写法
- 转:implementing cons/car/cdr without explicit storage
- Fish’s mission
- 遗传算法Matlab源程序
- Javaweb---服务器Tomcat配置
- Python系列之反射、面向对象
- 07 总结ProgressDialog 异步任务
- Guava Cache探索及spring项目整合GuavaCache实例
- APNs
- Connection lost: The server closed the connection
- JavaScript异步和单线程
- 编辑你的数学公式——markdown中latex的使用
- Excel图标布局,图表样式,图标元素
- yii框架的部署方法
- [翻译] JSAnimatedImagesView
热门文章
- Hadoop集群datanode死掉或者secondarynamenode进程消失处理办法
- RTX——第17章 定时器组
- 通过google浏览器的开发者工具修改cookie值
- 一款基于jquery和css3的响应式二级导航菜单
- 工厂模式——(Head first设计模式4)
- 怎样使GridView中满足某个条件的行可编辑,其余行不可编辑?
- Linux 下 tail 命令
- 分布式理论(4):Leases 一种解决分布式缓存一致性的高效容错机制(转)
- DataTable的AcceptChanges()和RejectChanges()方法
- rails局部模板 render