Leetcode N-Queens II
2016-12-26 09:14
225 查看
题意:要求输出N皇后问题的解的个数。
思路:返回解的个数。
另一种思路是不生成可行解,直接判断是否可行。判断是否可行有O(1)的方法。对于(x, y) 上的某个皇后,满足xi + yi = x + y和 n - xi + yi = x + y的位置都不能放置。
思路:返回解的个数。
class Solution { public: vector<vector<string> > re; int l; int totalNQueens(int n) { l = n; string ts; vector<string> tes; for(int i = 0; i < n; i ++) ts += '.'; for(int i = 0; i < n; i ++) tes.push_back(ts); dfs(tes, 0); return re.size(); } void dfs(vector<string> grid, int s) { if(s == l) { for(int i = 0; i < l; i ++) { for(int j = 0; j < l; j ++) { if(grid[i][j] == 'x') grid[i][j] = '.'; } } re.push_back(grid); return; } vector<string> mygrid; for(int i = 0; i < l; ++ i) { mygrid = grid; if(mygrid[s][i] == 'x') continue; if(mygrid[s][i] == '.') { mygrid[s][i] = 'Q'; for(int j = s + 1; j < l; j ++) mygrid[j][i] = 'x'; for(int j = i - 1, k = s + 1; j >=0 && k < l; j --, k ++) mygrid[k][j] = 'x'; for(int j = i + 1, k = s + 1; j < l && k < l; j ++, k ++) mygrid[k][j] = 'x'; //for(int it = 0; it < l; it ++) cout << mygrid[it] << endl; //cout << endl; dfs(mygrid, s + 1); } } return; } };
另一种思路是不生成可行解,直接判断是否可行。判断是否可行有O(1)的方法。对于(x, y) 上的某个皇后,满足xi + yi = x + y和 n - xi + yi = x + y的位置都不能放置。
class Solution { public: int count; int l; int totalNQueens(int n) { vector<bool> c1(n, false); vector<bool> c2(n * 2, false); vector<bool> c3(n * 2, false); count = 0; l = n; dfs(n, c1, c2, c3); return count; } void dfs(int row, vector<bool> c1, vector<bool> c2, vector<bool> c3) { if(row == 0) count ++; for(int i = 0; i < l; ++ i) { if(c1[i] || c2[row + i] || c3[l - row + i]) continue; else { c1[i] = true; c2[row + i] = true; c3[l - row + i] = true; dfs(row - 1, c1, c2, c3); c1[i] = false; c2[row + i] = false; c3[l - row + i] = false; } } } };
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- leetcode----Longest Substring Without Repeating Characters
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays