LeetCode N-Queens
来源:互联网 发布:魔力宝贝新手卡淘宝 编辑:程序博客网 时间:2024/05/16 04:50
N-Queens
Total Accepted: 5516 Total Submissions: 21906The 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.."]]
回溯+开数组记录之前选择
>.<这里不知道n的范围数组真的不好搞,无奈只有new一个了。注意关于C++new对内存初始化的情况,http://hi.baidu.com/maxy218/item/8cd098256327c1829d63d1ca
实际测试下来,加不加(),运行结果都是正确的,也就是说都初始化为0了,但是初始化是个好习惯!
然后由于返回值是字符串,于是对string构造函数又长了见识
string (size_t n, char c);
(6) fill constructor
Fills the string with n consecutive copies of character c.
class Solution { int *rec; bool *row, *l, *r;public: vector<vector<string> > solveNQueens(int n) { vector<vector<string> > ans; rec = new int[n](); row = new bool[n](); l = new bool[2 * n](); r = new bool[2 * n](); dfs(0, n, ans); delete(rec); delete(row); delete(l); delete(r); return ans; } void dfs(int s, int n, vector<vector<string> >& ans) { if (s == n) { vector<string> vec; for (int i = 0; i < n; i++) { string str(n, '.'); str[rec[i]] = 'Q'; vec.push_back(str); } ans.push_back(vec); return; } for (int i = 0; i < n; i++) { if (!row[i] && !l[s + i] && !r[s - i + n - 1]) { rec[s] = i; row[i] = true; l[s + i] = true; r[s - i + n - 1] = true; dfs(s + 1, n, ans); row[i] = false; l[s + i] = false; r[s - i + n - 1] = false; } } }};
0 0
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- leetcode 72: N-Queens
- LeetCode 38: N-Queens
- 【leetcode】N-Queens II
- 【leetcode】N-Queens
- LeetCode: N Queens II
- [LeetCode]N-Queens
- [LeetCode]N-Queens II
- [leetcode]N-Queens
- [LeetCode] Anagrams、N-Queens
- TCP,UDP,HTTP,FTP协议
- win32模版文件分析(VS2013)
- C++应用程序在Windows下的编译、链接:第三部分 静态链接(二)
- 解决 Jenkins配置任务的SVN路径时出错svn: E200015: OPTIONS ${SVN_URL} failed 的问题
- php jquery jsonp 跨域访问,jsoncallback无返回?!!!,无解了,为什么没返回,没返回!原来是是这个jsoncallback的问题
- LeetCode N-Queens
- 三和先生原稿 <易經大意> 下
- C++应用程序在Windows下的编译、链接(四)动态链接
- 第51条:当心字符串连接性能
- 一篇关于su和sudo以及visudo的很好的介绍性文档
- 关于VC写DLL文件产生的一个fatal errorc1083问题的解决办法
- java基础一些题目
- vim插件系列之cscope
- hdu 2899 Strange fuction(三分)