题意:
n皇后问题,输出n*n的棋盘摆放n个皇后的方案。
皇后攻击方式为同一行、同一列、同一斜线。
思路:
直接搜索。空间消耗方面,不需要申请整个棋盘大小,只要O(n)就够了,存某一行的皇后放在哪一列。
代码:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
int *column = new int[n];
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);
}
}
}
};