[LeetCode]N-Queens
来源:互联网 发布:空间站软件下载 编辑:程序博客网 时间:2024/06/07 12:39
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.."]【思路】回溯法解决。每次从棋盘的每一个行开始依次放旗子,如果莫一行全部位置都不能放那就回到上一行。基本思想类似与暴力求解,但是回溯法最大的优点是避免了无用的搜索,是一种编程技巧。简单来说,算法的伪代码如下:]
row = 1;//从第一行开始while(row>0){y[row]++; //为当前x位置找一个皇后的位置while(cannot_place) y[row]++; //找到合适的皇后if(y[row]<=N)//找到一个可以放置第x个皇后的位置,到该步为止,所求部分解都满足要求{//找到一个完整的放置方案{//存储结果}elserow++; //继续寻找下一个皇后的位置,还没找到完整解决方案}else//未找到可以放置第row行的皇后的位置,到该步为止,已经知道不满足要求{y[row] = 0;//因为要回溯置初始态,下一次是寻找第x-1个皇后的位置,//在下一次确定x-1的位置之后,第x个皇后的开始搜索的位置要重置row--; //回溯}}实现时有一些细节,比如能否放入皇后的判断,以及结果string的构建。这些我是通过子函数解决的。
class Solution {public: vector<vector<string> > solveNQueens(int n) { int row = 1; vector<int> y(n+1); vector<vector<string>> ret; vector<string> temp; while(row>0){ y[row]++;//在上一步基础上往前走 while((y[row]<=n) && (!check(row,y))) y[row]++;//走到第一个可解位置 if(y[row]<=n){ if(row==n){ storeRet(ret,temp,y,n);//如果可解,把结果存在ret中 } else row++; //继续往下找 } else{ y[row]=0; row -- ;//回溯找上一解 } } return ret; } bool check(int row,vector<int> y) { for(int j = 1;j < row;j++) if((abs(row-j) == abs(y[j] - y[row]))||(y[j] == y[row])) //判断插入是否有效 return false; return true; } void storeRet(vector<vector<string> > &ret,vector<string>temp,vector<int> y,int n){ string a; for(int i=0;i<n;++i){ a+='.'; } for(int i=0;i<n;++i){ temp.push_back(a); } for( int i=1; i<=n; i ++ ) { for( int j=1; j<=n; j++ ) if( j==y[i] ) temp[i-1][j-1]='Q'; } ret.push_back(temp); }};
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
- SSH框架搭建与项目实践步骤
- sbl1功能模块 -- 重启与下载模式
- Hadoop之——正常启动而无法正常关闭
- 二叉树、HuffmanTree、HuffmanCode的实现
- 芯片的电源和地管脚名称
- [LeetCode]N-Queens
- 常见的Android框架
- sbl1功能模块 -- 三色灯键盘灯与振动器
- R语言应用
- 简单sql部分强化练习题
- NSCalendar + NSDateComponents
- easyui 中datagrid的使用方法
- 利用ant脚本 自动构建svn增量/全量 系统程序升级包
- 大牛的博客里面好东西简单易用长知识