52.多皇后问题第二弹
来源:互联网 发布:win 7设置家庭网络 编辑:程序博客网 时间:2024/06/06 00:34
N-Queens II
问题描述:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
测试代码(C++):
int totalNQueens(int n) { vector<bool> col(n, true); vector<bool> anti(2*n-1, true); vector<bool> main(2*n-1, true); vector<int> row(n, 0); int count = 0; dfs(0, row, col, main, anti, count); return count;}void dfs(int i, vector<int> &row, vector<bool> &col, vector<bool>& main, vector<bool> &anti, int &count) { if (i == row.size()) { count++; return; } for (int j = 0; j < col.size(); j++) { if (col[j] && main[i+j] && anti[i+col.size()-1-j]) { row[i] = j; col[j] = main[i+j] = anti[i+col.size()-1-j] = false; dfs(i+1, row, col, main, anti, count); col[j] = main[i+j] = anti[i+col.size()-1-j] = true; } }}
测试代码(python):
class Solution(object): def totalNQueens(self, n): self.res = 0 self.dfs([-1]*n, 0) return self.res def dfs(self, nums, index): if index == len(nums): self.res += 1 return for i in xrange(len(nums)): nums[index] = i if self.valid(nums, index): self.dfs(nums, index+1) def valid(self, nums, n): for i in xrange(n): if nums[i] == nums[n] or abs(nums[n]-nums[i]) == n-i: return False return True
性能:
阅读全文
0 0
- 52.多皇后问题第二弹
- 51.多皇后问题
- 皇后问题
- 皇后问题
- 皇后问题
- 皇后问题
- 皇后问题
- 皇后问题
- 皇后问题!
- 皇后问题
- 皇后问题
- 皇后问题
- 皇后问题
- SICP_Python第二章:映射(子集问题,排列问题,N皇后问题)
- 八皇后 n皇后 问题
- 八皇后N皇后问题
- week8(第二波搜索进阶) A -hdu 2553 N皇后问题
- 8皇后问题和N皇后问题
- a标签中"#"和"javascript:void(0)"的区别
- LeetCode 120 Triangle
- java通过配置文件jdbc.properties链接Oracle数据库工具类
- java swing 树型结构
- Java 3DES加密解密(Commons.Codec Base64)
- 52.多皇后问题第二弹
- Eclipse快捷键大全(转载)
- Python中dict的特点
- Android 自定义广播接收器
- ImageView.ScaleType的解释
- MTCNN(Multi-task convolutional neural networks)人脸对齐
- Ubuntu基于docker的二节点geth私链
- Dialog等待框
- Apache2.4源码编译安装的依赖问题