LeetCode C++ 51. N-Queens【回溯】困难
发布日期:2021-07-01 02:51:02
浏览次数:2
分类:技术文章
本文共 1919 字,大约阅读时间需要 6 分钟。
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 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
Input: 4Output: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
题意:返回N皇后的具体方案。
思路:做过很多次的题目了,就是形成方案的时候有点麻烦。代码如下:
class Solution { public: vector colNote; //记录之前的每行(以1开始)的列号 vectorcolVis; //记录列号是否被使用过 vector > ans; //记录答案 string rowstr; //记录每行的字符串答案 int endGame; bool check(int row, int col) { for (int j = 0; j < row; ++j) if (abs(col - colNote[j]) == abs(row - j)) //和前几行是否成对角线 return false; return true; } void dfs(int row) { if (row >= endGame) { vector tmp; for (int i = 0; i < colNote.size(); ++i) { //得到每行的列号 tmp.push_back(rowstr); tmp[i][colNote[i]] = 'Q'; //原来记录的行列都从1开始 } ans.push_back(tmp); return; } for (int i = 0; i < endGame; ++i) { if (!colVis[i] && check(row, i)) { //和前几行的列号是否相等或者成对角线 colNote[row] = i; colVis[i] = true; dfs(row + 1); colVis[i] = false; } } } vector > solveNQueens(int n) { if (n == 0 || n == 2 || n == 3) return vector >(); colNote.resize(n, 0); colVis.resize(n, false); endGame = n; rowstr.resize(n, '.'); dfs(0); //从第0行开始 return ans; }};
感觉写的不咋地,但还是比Python快得多:
转载地址:https://memcpy0.blog.csdn.net/article/details/108395562 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年05月05日 19时54分17秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
填入空隙(setbkcolor,setbkmode)
2019-05-02
[收藏] FC交换机基础知识详解
2019-05-02
NVMe技术架构深度分析
2019-05-02
技术爆炸时代如何做技术的掌控者?
2019-05-02
机柜服务器如何选择,有哪些学问?
2019-05-02
Ceph存储系统Scrub机制分析
2019-05-02
OpenStack重组,敢问未来路在何方?
2019-05-02
CTO,是怎样炼成的?
2019-05-02
选择GPU服务器的基本原则
2019-05-02
关于数据中台系统,需要了解哪些技术?
2019-05-02
全面分析HDFS基本技术原理
2019-05-02
详解以太网介质技术发展史!
2019-05-02
详解“硬核”虚拟化技术SR-IOV原理
2019-05-02
SAP HANA解决方案设计10问详解
2019-05-02
详解内存运算架构、挑战和趋势
2019-05-02
Lightbits能否让NVMe/TCP新标准旗开得胜?
2019-05-02
数据中台,何为正解?!
2019-05-02
架构师进阶必看!架构师的工作都干些什么?
2019-05-02
详解RDMA架构和技术原理
2019-05-02
Virtio技术架构简明分析
2019-05-02