[Leetcode] 52. N-Queens II 解题报告
2017-01-11 15:05
609 查看
题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路:
和Leetcode 51思路完全一致。不过因为只需要返回符合条件的解的个数,所以可以在Leetcode 51的基础上做适当优化:我们仅仅用一个一维数组来表示棋盘,即board[i] = j意味着在第i行的皇后放在第j列。如果board[i] == -1,则表示该行上尚未放置皇后。此时对安全性的检查也会变得更加简单,如下代码中的safe函数所示。
代码:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路:
和Leetcode 51思路完全一致。不过因为只需要返回符合条件的解的个数,所以可以在Leetcode 51的基础上做适当优化:我们仅仅用一个一维数组来表示棋盘,即board[i] = j意味着在第i行的皇后放在第j列。如果board[i] == -1,则表示该行上尚未放置皇后。此时对安全性的检查也会变得更加简单,如下代码中的safe函数所示。
代码:
class Solution { public: int totalNQueens(int n) { int ret = 0; vector<int& 4000 gt; board(n, -1); DFS(ret, board, n, 0); return ret; } private: void DFS(int& ret, vector<int>&board, int n, int row) { if(row == n) { ++ret; return; } for(int i = 0; i < n; ++i) // check each col in this row { if(safe(board, row, i, n)) { board[row] = i; DFS(ret, board, n, row + 1); board[row] = -1; } } } bool safe(vector<int>&board, int row, int col, int n) { int val1 = row - col; int val2 = row + col; int temp = 0; for(int i = 0; i < row; ++i) // check the previous rows { if(board[i] == col) return false; temp = i - val1; if(temp >= 0 && temp < n && board[i] == temp) return false; temp = val2 - i; if(temp >= 0 && temp < n && board[i] == temp) return false; } return true; } };
相关文章推荐
- AndroidStudio导入项目一直卡在Building gradle project info
- 购物车里面的加减按钮
- UEditor上传图片到项目外部目录-java
- UEditor 第一次加载正常,第二次无法正常加载问题
- 百度编辑器UEditor不能插入视频的解决方法
- 百度编辑器UEditor不能插入视频的解决方法
- 我的MVP呢?
- DP (7) -- Ones and Zeroes, Longest Increasing Subsequence, Perfect Squares
- 利用ueditor的文件上传功能上传文件到外部服务器的地址&&&&&字符统计功能重写
- [Leetcode] 51. N-Queens 解题报告
- iOS UITextField限制输入长度
- IPNC_RDK_McFW_UserGuide
- Deep Analysis UIImageJPEGRepresentation&UIImagePNGRepresentation
- MySQL提示:The server quit without updating PID file问题的解决办法
- No value specified for Date解决方法
- qt, connect参数,Qt::DirectConnection,Qt::QueuedConnection
- [置顶] 基于Duilib的多标签浏览器(IE内核)
- 001HTC VIVE GUI界面
- 24、Power Query-数学运算的应用(统计男女人数)
- 在T-SQL语句中访问远程数据库(openrowset/opendatasource/openquery)