LeetCode 51 N-Queens
2017-05-25 21:51
302 查看
题意:
n皇后问题,输出n*n的棋盘摆放n个皇后的方案。
皇后攻击方式为同一行、同一列、同一斜线。
思路:
直接搜索。空间消耗方面,不需要申请整个棋盘大小,只要O(n)就够了,存某一行的皇后放在哪一列。
代码:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
int *column = new int
;
vector<vector<string>> ans;
dfs(0, n, column, ans);
return ans;
}
private:
void dfs(int row, int total, int *column, vector<vector<string>> &ans) {
if (row == total) {
vector<string> part;
for (int i = 0; i < total; ++i) {
stringstream ss;
for (int j = 0; j < total; ++j) {
if (column[i] == j) {
ss << 'Q';
} else {
ss << '.';
}
}
part.push_back(ss.str());
}
ans.push_back(part);
return;
}
for (int i = 0; i < total; ++i) {
bool can = true;
for (int j = 0; j < row; ++j) {
if (i == column[j] || i == column[j] - (row - j) || i == column[j] + (row - j)) {
can = false;
break;
}
}
if (can) {
column[row] = i;
dfs(row + 1, total, column, ans);
}
}
}
};
n皇后问题,输出n*n的棋盘摆放n个皇后的方案。
皇后攻击方式为同一行、同一列、同一斜线。
思路:
直接搜索。空间消耗方面,不需要申请整个棋盘大小,只要O(n)就够了,存某一行的皇后放在哪一列。
代码:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
int *column = new int
;
vector<vector<string>> ans;
dfs(0, n, column, ans);
return ans;
}
private:
void dfs(int row, int total, int *column, vector<vector<string>> &ans) {
if (row == total) {
vector<string> part;
for (int i = 0; i < total; ++i) {
stringstream ss;
for (int j = 0; j < total; ++j) {
if (column[i] == j) {
ss << 'Q';
} else {
ss << '.';
}
}
part.push_back(ss.str());
}
ans.push_back(part);
return;
}
for (int i = 0; i < total; ++i) {
bool can = true;
for (int j = 0; j < row; ++j) {
if (i == column[j] || i == column[j] - (row - j) || i == column[j] + (row - j)) {
can = false;
break;
}
}
if (can) {
column[row] = i;
dfs(row + 1, total, column, ans);
}
}
}
};
相关文章推荐
- LeetCode(51) N-Queens
- LeetCode 51 - N-Queens
- [leetcode]51. N-Queens
- leetcode-51-N-Queens
- leetCode 51. N-Queens | 回溯问题(N皇后问题) | hard
- LeetCode 51 N-Queens
- LeetCode 51. N-Queens
- LeetCode51 N-Queens
- LeetCode 51. N-Queens
- LeetCode_51---N-Queens
- LeetCode 51. N-Queens
- 【LeetCode】51.N-Queens(hard)解题报告
- leetcode51/52-N-Queens I/II(n皇后问题)
- LeetCode 51. N-Queens 题解
- 51. N-Queens Leetcode Python
- LeetCode 51.N-Queens
- Leetcode 51. N-Queens && 52. N-Queens II(Hard)
- leetcode解题笔记 51.N-Queens [Hard]
- LeetCode 51. N-Queens(N皇后问题Ⅰ)
- leetCode 51.N-Queens (n皇后问题) 解题思路和方法