51.leetcode N-Queens(hard)[递归回溯剪枝]
来源:互联网 发布:一个淘宝号能刷几单 编辑:程序博客网 时间:2024/06/11 14:52
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.."]]
八皇后问题的关键是每个皇后不在同一列同一行,并且不在同一对角线。那么首先我们可以默认每个皇后不在同一行,即每一行一个皇后。用一个状态数组status保存每行的皇后所在的列数,此时对于每个皇后可以放置的列数是0~n-1遍历,并且检查该行之前放置的皇后的列数位数会不会导致当前皇后与其他皇后引起攻击。因此用valid函数检查此行填写的列数是否合法,如果合法则往下走填写后面行的列数,当填写完所有行的列数,此时就得到一个合法的解。但是此时得到的不是string的表达形式,需要通过changeToString函数转换成string的形式。
class Solution {public: void changeToString(vector<int> &status,vector<vector<string> >&result) { int n = status.size(); vector<string> temp; for(int i=0;i<n;i++) { string s = ""; for(int j=0;j<n;j++) { if(status[i] != j) s += '.'; else s += 'Q'; } temp.push_back(s); } result.push_back(temp); } bool valid(int cols,int row,int n, vector<int> &status) { for(int i=0;i<row;i++) { if(status[i] == cols || abs(status[i]-cols) == abs(i-row)) return false; } return true; } void getQueens(int row,int n,vector<int> &status,vector<vector<string> >&result) { if(row == n) //此时表示一个合法的皇后棋盘已经产生 { changeToString(status,result); }else{ for(int i= 0;i<n;i++) { if(valid(i,row,n,status)) { status[row] = i; getQueens(row+1,n,status,result); status[row] = -1; } } } } vector<vector<string>> solveNQueens(int n) { vector<vector<string> > result; if(n <= 0) return result; vector<int>status(n,-1); getQueens(0,n,status,result); return result; }};
0 0
- 51.leetcode N-Queens(hard)[递归回溯剪枝]
- LeetCode 51. N-Queens 回溯
- Leetcode 51. N-Queens && 52. N-Queens II(Hard)
- leetcode---N-Queens---回溯
- Leetcode 51. N-Queens (Hard) (cpp)
- leetcode解题笔记 51.N-Queens [Hard]
- 【Leetcode】51. N-Queens(回溯)
- 51. N-Queens Hard
- leetcode hard模式专杀之51. N-Queens
- N-Queens C++递归回溯实现
- leetcode 51. N-Queens 回溯算法的应用
- [Leetcode 51, hard] N-Queens I
- [Leetcode 52, Hard] N Queens II
- Leetcode 52. N-Queens II (Hard) (cpp)
- LeetCode OJ - N-Queens 回溯法
- leetcode 51 N-Queens 回溯 万能结构
- N-Queens(递归回溯+迭代回溯)
- LeetCode 51. N-Queens
- 干掉你的StringUtils字符工具类
- web获取访问真实IP
- 自己实现JTopo插件的圆形布局
- codevs 1128 导弹拦截
- quartz时间设置
- 51.leetcode N-Queens(hard)[递归回溯剪枝]
- RasGetCountryInfo
- 【Android UI设计与开发】8.顶部标题栏(一)ActionBar 奥义·详解
- Android NDK之JNI异常处理
- RabbitMQ安装教程(Windows/Linux都有)
- 表格:增加、删除行,鼠标移动改变行背景色,行内文本框自适应td,a除下划线(使用节点实现)
- org.apache.ibatis.exceptions.PersistenceException
- [LeetCode] Intersection of Two Arrays(java)
- [noip模拟赛]敲砖块(dp)