一. 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..”]
]
Difficulty:Hard
TIME:40MIN
解法
N皇后问题也是搜索的经典问题,但是论复杂度来说,Sudoku Solver会稍微难一点。因此如果会解决数独,那么这道题也就没什么特别大的问题。
首先,这道题不像数独需要每次取最可能的点才是最优的搜索路线,而这道题如果每行从左到右依次搜索,其实就是最优的搜索路线了。而且考虑的问题也比较简单,就是能不能放的问题(true和false的问题),不像数独会考虑0-9几种情况。
不过就算是true和false的问题,由于考虑到回溯的原因,还是采用递增递减的策略比较好(如果该位置不能填则加一,回溯的时候减一,等于0说明可以填),这样就不会在回溯的时候无法准确还原搜索之前棋盘的样貌。
void dfs(vector<vector<string>> &result, vector<string> &v, vector<vector<int>> &m, int index) {
if(index == v.size()) {
result.push_back(v);
return;
}
for(int i = 0; i < v.size(); i++) {
if(m[index][i] == 0) {
v[index][i] = 'Q';
for(int j = 0; j + index + 1 < v.size(); j++) {
m[j + index + 1][i]++;
if(i - j - 1 >= 0)
m[j + index + 1][i - j - 1]++;
if(i + j + 1 < v.size())
m[j + index + 1][i + j + 1]++;
}
dfs(result, v, m, index + 1);
//还原棋盘,由于之前以为单纯true和false就可以,导致无法准确还原棋盘样貌
for(int j = 0; j + index + 1 < v.size(); j++) {
m[j + index + 1][i]--;
if(i - j - 1 >= 0)
m[j + index + 1][i - j - 1]--;
if(i + j + 1 < v.size())
m[j + index + 1][i + j + 1]--;
}
v[index][i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> v(n,string(n,'.'));
vector<vector<int>> m(n, vector<int>(n, 0)); //取一个数组用来递增递减,判断能否填入
dfs(result, v, m, 0);
return result;
}
代码的时间复杂度不大于 O(n!) 。