N-Queens N皇后放置问题 回溯法
2015-07-09 19:30
453 查看
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.."] ]
Hide Tags
Backtracking
class Solution { public: vector<vector<string> > res; vector<vector<string>> solveNQueens(int n) { int *a=new int ; memset(a,0,sizeof(int)*n); solve(a,n,0); return res; } void solve(int *a, int n,int index) { for(int i=0;i<n;i++)//对每个index 寻找第i列放皇后 { if(isValid(a,n,index,i))//index i 行 列 { a[index]=i; if(index==n-1) { print(a,n); a[index]=0; return ; } solve(a,n,index+1); a[index]=0; } } } void print(int *a, int n) { vector<string> path; for(int i=0;i<n;i++) { string s(n,'.'); s[a[i]]='Q'; path.push_back(s); } res.push_back(path); } bool isValid(int *a,int n,int x,int y) { int col; for(int i=0;i<x;i++)//行 { col=a[i];//第i行,皇后在第col列 if(y==col) //同列 return false; if((col-y)==(i-x))// 对角线'\' return false; if((col-y)==(x-i))// 对角线'/' return false; } return true; } };
相关文章推荐
- 配置duilib教程
- UI_UITableView_搭建
- UpMarqueeTextView-模仿淘宝客户端向上滚动的广告条
- (or type control -D to continue)
- For多重循环 break continue
- Set-UID程序漏洞实验
- NGUI奇葩的collider不能触发的问题处理
- /mongod: /usr/lib64/libssl.so.10: no version information available (required by ./mongod)
- TOJ 4101 Guess Game
- CustomBuild:拒绝访问。 error MSB6006: "cmd.exe" exited with code 1.
- [IOS]UITextField限制字符输入
- uitoolbar item 自动调整布局
- 初学qt 用qt做的图片查看器超级简陋(按照《Qt quick核心编程》一书敲的)
- UI设计公司
- c# HttpWebRequest与HttpWebResponse请求网页和返回网页教程
- SQL Server VALUES 使用一记住
- easyui 给文本框 checkbox赋值问题
- 提高Interface Builder高效工作的8个技巧
- iOS UIScrollViewDelegate详解
- iOS UITableView表视图滚动隐藏UINavigationController导航栏