LeetCode:N-Queens
2016-06-08 19:14
429 查看
N-Queens
Total Accepted: 55554 TotalSubmissions: 212496 Difficulty: Hard
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.."] ]
Subscribe to see which companies asked this question
Hide Tags
Backtracking
Hide Similar Problems
(H) N-Queens II
思路:
将N-Queens II中的解做一个转化即可。
c++ code:
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; vector<int> nums(n); for(int i=0;i<n;i++) nums[i]=i; permute(res, nums,0); return res; } // 自定义函数 void permute(vector<vector<string>> &res, vector<int> &nums, int pos) { int n = nums.size(); if(pos==n) { if(check(nums)) { vector<string> ans; for(int i=0;i<n;i++) { string str(n, '.'); str[nums[i]] = 'Q'; ans.push_back(str); } res.push_back(ans); } return; } for(int i=pos;i<n;i++) { swap(nums[pos], nums[i]); permute(res, nums, pos+1); swap(nums[i], nums[pos]); } } bool check(vector<int> &nums) { int n = nums.size(); for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) // 判断是否在主、副对角线上 if(i-j == nums[i]-nums[j] || j-i == nums[i]-nums[j]) return false; } return true; } };
相关文章推荐
- 在Qt中生成UUID(全球唯一码)
- vue 多项目 依赖webpack开发共用 配置
- poj1458Common Subsequence--LCS
- LeetCode:N-Queens II
- 有关StringBuilder字符串的一些应用
- Looper、Message、MessageQueue、Handler异步消息处理机制源码分析
- 检测预设资源是否有UIFont为空的编辑器
- Android学习之图解调用invalidate()和requestLayout()的过程
- Parquet 读写
- 栈(stack)和队列(queue)的简单实例
- UIAlertController
- UIView的drawRect调用时机和条件
- 栈和队列的简单实例
- RequireJS入门(一)
- BearSkill之UIView挖空处理
- ios UIView常用动画效果
- 关于easyui 行高禁止自适应
- Android中常用的handler进行UI更新和Thread代码
- .MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1
- while(true)引发的Dubbo应用假死