Leetcode: N-Queens
2014-01-11 21:22
453 查看
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
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
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
搞到很久,一个变量写错了,总是报Memory Limit Exceeded,郁闷。
![](http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png)
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.."] ]
搞到很久,一个变量写错了,总是报Memory Limit Exceeded,郁闷。
class Solution { public: vector<vector<string> > solveNQueens(int n) { solveNQueensUtil(0, n); return result; } void solveNQueensUtil(int step, int n) { if (step == n) { print(n); return; } for (int i = 0; i < n; ++i) { cols.push_back(i); if (canPutQueen(step)) { solveNQueensUtil(step + 1, n); } cols.pop_back(); } } bool canPutQueen(int step) { for (int i = 0; i < step; ++i) { if (cols[step] == cols[i] || abs(step - i) == abs(cols[step] - cols[i])) { return false; } } return true; } void print(int n) { vector<string> solve; for (int i = 0; i < n; ++i) { string line; for (int j = 0; j < n; ++j) { line.push_back(cols[i] == j ? 'Q' : '.'); } solve.push_back(line); } result.push_back(solve); } private: vector<int> cols; vector<vector<string> > result; };
相关文章推荐
- leetcode Two Sum
- leetcode Median of Two Sorted Arrays
- leetcode Longest Substring Without Repeating Characters
- leetcode Add Two Numbers
- leetcode Longest Palindromic Substring
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- [LeetCode] Distinct Subsequences
- [LeetCode] Flatten Binary Tree to Linked List
- [LeetCode] Path Sum
- [LeetCode] Path Sum II
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- [LeetCode] Balanced Binary Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Binary Tree Level Order Traversal II
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Maximum Depth of Binary Tree