N-Queens

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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

这题和Sudoku Solver是一个套路,回溯法尝试所有可能性,将可行解的保存起来。可以对比着看。

由于这里路径尝试本质上是有序的,即1~9逐个尝试,因此无需额外设置状态位记录已经尝试过的方向。

我们先用vector<int>来存放可行解,下标代表行号,元素代表列号。

因此上图中Solution 1用vector<int>表示就是[1,3,0,2]

解题流程就是在下一行中尝试列数(0~n-1),如果可行则递归下去,如果不可行则弹出继续尝试下一列。

最后将vector<vector<int> > 转为vector<vector<string> >即可。

class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
return convert(solve(n), n);
}
vector<vector<int> > solve(int n)
{
vector<vector<int> > ret;
vector<int> cur;
Helper(ret, cur, , n);
return ret;
}
void Helper(vector<vector<int> >& ret, vector<int> cur, int pos, int n)
{
if(pos == n)
ret.push_back(cur);
else
{
for(int i = ; i < n; i ++)
{
cur.push_back(i);
if(check(cur))
Helper(ret, cur, pos+, n);
cur.pop_back();
}
}
}
bool check(vector<int> cur)
{
int size = cur.size();
int loc = cur[size-];
for(int i = ; i < size-; i ++)
{
if(cur[i] == loc)
return false;
else if(abs(cur[i]-loc) == abs(i-size+))
return false;
}
return true;
}
vector<vector<string> > convert(vector<vector<int> > ret, int n)
{
vector<vector<string> > retStr;
for(int i = ; i < ret.size(); i ++)
{
vector<string> curStr;
for(int j = ; j < n; j ++)
{
string loc(n, '.');
loc[ret[i][j]] = 'Q';
curStr.push_back(loc);
}
retStr.push_back(curStr);
}
return retStr;
}
};

【LeetCode】51. N-Queens的更多相关文章

  1. 【LeetCode】51. N-Queens 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  2. 【LEETCODE】51、数组分类,简单级别,题目:581,830,1010,665

    package y2019.Algorithm.array; /** * @ClassName FindUnsortedSubarray * @Description TODO 581. Shorte ...

  3. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  4. 【Leetcode】Pascal&#39;s Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  5. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

  6. 27. Remove Element【leetcode】

    27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...

  7. 【刷题】【LeetCode】007-整数反转-easy

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...

  8. 【刷题】【LeetCode】000-十大经典排序算法

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接 000-十大经典排序算法

  9. 【leetcode】893. Groups of Special-Equivalent Strings

    Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-o ...

随机推荐

  1. django的单元测试框架unittest、覆盖率

    django的单元测试 指定测试范围: 指定运行某些测试文件./manage.py test --pattern="tests_*.py" -v 2 运行所有测试文件./manag ...

  2. C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数

    在编程中经常需要用到数字与字符串的转换,下面就总结一下. 1.atoi() C/C++标准库函数,用于字符串到整数的转换. 函数原型:int atoi (const char * str); #inc ...

  3. 20个代码生成框架 (.NET JAVA)

    1.1 CodeSmith 一款人气很旺国外的基于模板的dotnet代码生成器 官方网站:http://www.codesmithtools.com 官方论坛:http://forum.codesmi ...

  4. 记录C#错误日志工具

    在编程过程中,我们经常会用try...catch处理可能出错的代码块.如果程序出现错误,则直接show出错误信息. 当然,大型的系统都有错误日志处理模块,用数据库记录错误日志信息,有相应的写入错误日志 ...

  5. 基础学习:C#中float的取值范围和精度

    float类型的表现形式: 默认情况下,赋值运算符右侧的实数被视为 double. 因此,应使用后缀 f 或 F 初始化浮点型变量,如以下示例中所示: float x = 3.5F; 如果在以上声明中 ...

  6. COM中的HRESULT

  7. [NPM] Execute npx commands with $npm_ Environment Variables

    We will incorporate npm specific environment variables when executing various npx commands. In our e ...

  8. [Node.js]26. Level 5 : Route rendering

    Instead of just writing out the quote to the response, instead render the quote.ejs template, passin ...

  9. linux下线刷硬盘

    Linux系统往往有添加磁盘不够的情况,这时就需要添加新的硬盘.一般情况下需要重启服务器,这里我们来使用线刷方式读取Linux新增硬盘 1.添加磁盘后fdisk -l磁盘没有显示 2.查看主机总线号 ...

  10. W3CSchool CSS学习简记

    什么是 CSS?   CSS 指层叠样式表 (Cascading Style Sheets) 样式定义如何显示 HTML 元素 样式通常存储在样式表中 把样式添加到 HTML 4.0 中,是为了解决内 ...