116. N-Queens
2016-07-06 08:40
411 查看
-51. N-Queens QuestionEditorial Solution My Submissions
Total Accepted: 57241
Total Submissions: 215678
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:
思路:深搜+剪枝
Total Accepted: 57241
Total Submissions: 215678
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:
思路:深搜+剪枝
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; vector<int> vis(n,0),resid(n,0); vector<string> vs; solveNQueens2(n,res,resid,vs,vis,0); return res; } void solveNQueens2(int n,vector<vector<string>> &res,vector<int> resid,vector<string> vs,vector<int> vis,int j) { if(j==n){ res.push_back(vs); } else{ string s(n,'.'); for(int i=0;i<n;++i){ if(vis[i]==0){ vis[i]=1; s[i] = 'Q'; resid[j]=i; if(!isLegal(resid,j,i)){ s[i] = '.'; vis[i]=0; continue; } vs.push_back(s); solveNQueens2(n,res,resid,vs,vis,j+1); vs.erase(vs.end()-1); s[i] = '.'; vis[i]=0; } } } } bool isLegal(const vector<int> &resid,int row,int col) { for(int i=0;i<row;++i){//是否在同一对角线上 if(abs(col-resid[i])==abs(row-i))return false; } return true; } };
相关文章推荐
- Android MessageQueue与Message详解
- .NET平台开源项目速览(17)FluentConsole让你的控制台酷起来
- HDU 5288 OO’s Sequence (数论)
- pyhton中的Queue(队列)
- 易语言UI设计体会
- BZOJ2656 [Zjoi2012]数列(sequence)
- easyui
- Random Number Series Questions
- Unique Paths | & ||
- Binary Tree Longest Consequence
- N-Queens | & N-Queens II
- MySQL: Tree-Hierarchical query
- 陶哲轩实分析-第18章 Lebesgue测度
- Range Sum Query 2D
- Next Larger Value in BST
- LeetCode--No.357--Count Numbers with Unique Digits
- The Concept of Indistinguishability under Chosen Plaintext Attack (IND-CPA)
- UITableView滚动时NSTimer不执行
- 【Leetcode】303 Range Sum Query - Immutable - 【动态规划】
- Codeforces Round #360 (Div. 2) -- E. The Values You Can Make (DP)