博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: n-queen, n-queen II
阅读量:6934 次
发布时间:2019-06-27

本文共 2013 字,大约阅读时间需要 6 分钟。

思路:

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

总结:

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

代码:

#include 
#include
#include
using namespace std;class Solution {public: int N; vector
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 
#include
#include
using namespace std;class Solution {public: int N; vector
pos; vector
> 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
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
> solveNQueens(int n) { pos.clear(); result.clear(); memset(visited, 0, sizeof(visited)); N = n; dfs(0); return result; }};

  

转载地址:http://eggjl.baihongyu.com/

你可能感兴趣的文章
python 在windows 中文显示
查看>>
路由器后面再接一个路由器怎么设置(二级路由)
查看>>
python 调用shell命令的方法
查看>>
.Net转Java.02.数据类型
查看>>
在一个gradle 的maven property 里添加多个URL
查看>>
PHP中的SESSION
查看>>
C#正则表达式的完全匹配、部分匹配及忽略大小写的问题
查看>>
【游戏开发】基于VS2017的OpenGL开发环境搭建
查看>>
洛谷P3960 列队(动态开节点线段树)
查看>>
RESTful到底是什么玩意??
查看>>
PHP的词法解析器:re2c
查看>>
Html5版本的全套股票行情图开源了,附带实现技术简介
查看>>
Our Proof : Page Scraping : Website Data Extraction : Data Mining Analytics : Connotate.com
查看>>
linux 时间戳及时间差计算
查看>>
[Dynamic Language] Python 静态方法、类方法、属性
查看>>
在 Delphi 下使用 DirectSound (5): 获取或设置缓冲区的格式:
查看>>
select 语句的执行顺序
查看>>
wayos利用easyradius实现WEB认证页面的记住密码及到期提醒功能
查看>>
软件工程 软件的估计为什么这么难
查看>>
struts2标签
查看>>