LeetCode 51. N-Queens
题目
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
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..”]
]
思路
n皇后问题算是非常经典的问题了,根据规则我们可以注意到,每一行和每一列上最多只能有一个皇后,而n行的图中我们要获得n个皇后,所以每一行上必须有一个皇后。我们可以根据这个特征优化我们的遍历过程。
我用了迭代的方式来遍历,一次迭代只处理一行的数据,并每次迭代都记录当前已放皇后数量。
这题的关键就在于根据题意,不断地优化遍历的过程。
每一行上必须有一个皇后
每次放下皇后后,只用计算其对接下来的行拥有的可放位置带来的影响
实现代码
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
solveNQueens_iterator(0, vector<string>(n, string(n, ' ')), result, 0);
return result;
}
void solveNQueens_iterator(int i, vector<string> map, vector<vector<string>>& result, int num) {
if (num == map.size())result.push_back(map);
if (i == map.size())return;
for (int j = 0; j < map.size(); j++)
if (map[i][j] == ' ')solveNQueens_iterator(i + 1, print_point(map, i, j), result, num + 1);
}
vector<string> print_point(vector<string> map, int x, int y)
{
for (int i = 0; i < map.size(); i++)
{
map[x][i] = '.';
map[i][y] = '.';
if (x + i < map.size() && y + i < map[0].size())map[x + i][y + i] = '.';
if (x + i < map.size() && y - i >= 0)map[x + i][y - i] = '.';
}
map[x][y] = 'Q';
return map;
}
};