您的位置:首页 > 产品设计 > UI/UE

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);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: