LeetCode OJ N-Queens II
来源:互联网 发布:淘宝五线谱乐器专营店 编辑:程序博客网 时间:2024/06/05 14:14
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
follow up the question N queens.
class Solution { public: int totalNQueens(int n) { return solveNQueens(n).size(); } vector<vector<string> > solveNQueens(int n) { NLine = n; w = n; h = n; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { chessBoard[i][j] = '.'; } } ans.clear(); // notice that this class may be used to solve a question more than one time DFS(0); return ans; } void DFS(int nowLine) { if (nowLine == NLine) { // have got the answer writeIn(); return; } for (int j = 0; j < NLine; j++) { if (isValid(nowLine, j)) { chessBoard[nowLine][j] = 'Q'; DFS(nowLine + 1); chessBoard[nowLine][j] = '.'; } } } bool isValid(int i, int j) { // to judge if a position is valid to put a queen for (int k = 0; k < w; k++) { if (chessBoard[i][k] == 'Q') return false; // from left to right if (chessBoard[k][j] == 'Q') return false; // from up to down } for (int k = 0; k < h; k++) { if (inBoard(i + 1 * k, j + 1 * k) && chessBoard[i + 1 * k][j + 1 * k] == 'Q') return false; // from leftUp to rightDown if (inBoard(i - 1 * k, j - 1 * k) && chessBoard[i - 1 * k][j - 1 * k] == 'Q') return false; // from rightDown to leftUp if (inBoard(i - 1 * k, j + 1 * k) && chessBoard[i - 1 * k][j + 1 * k] == 'Q') return false; // from leftDown to rightUp if (inBoard(i + 1 * k, j - 1 * k) && chessBoard[i + 1 * k][j - 1 * k] == 'Q') return false; // from rightUp to leftDown } return true; } bool inBoard(int i, int j) { return 0 <= i && i < h && 0 <= j && j < w; } void writeIn() { vector<string> ansPart; for (int i = 0; i < h; i++) { string temp; for (int j = 0; j < w; j++) { temp.push_back(chessBoard[i][j]); } ansPart.push_back(temp); } ans.push_back(ansPart); } private: char chessBoard[16][16]; int NLine; int w, h; vector<vector<string> > ans;};
0 0
- LeetCode OJ:N-Queens II
- LeetCode OJ - N-Queens II
- LeetCode OJ N-Queens II
- <LeetCode OJ> 52. N-Queens II
- LeetCode OJ 之 N-Queens II(N皇后 - 二)
- LeetCode OJ:N-Queens
- LeetCode OJ - N-Queens
- LeetCode OJ N-Queens
- LeetCode: N-Queens II
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- 【leetcode】N-Queens II
- LeetCode: N Queens II
- [LeetCode]N-Queens II
- LeetCode - N-Queens II
- LeetCode:N-Queens II
- 【leetcode】N-Queens II
- LeetCode:N-Queens II
- 7. tictactoe终于调试完成
- LeetCode OJ Anagrams
- 通过Tooz在python中实现分布式群组和锁管理
- Android学习笔记の九
- 创建pdf模板
- LeetCode OJ N-Queens II
- html5简单游戏编程从零开始
- Rotate Array(旋转队列)
- Linux程序设计(Linux shell编程十三)
- LeetCode OJ N-Queens
- 判断链表是否相交
- LeetCode OJ Sudoku Solver
- [LeetCode]Convert Sorted List to Binary Search Tree
- 题3