一般遇到N皇后问题,就涉及到回溯算法(backtrace)。回溯算法一般可以用来解决集合,子集,排列,组合,地图路线,字符串路径等问题。
下面来总结一下回溯算法的模板:
if(终止条件) //判断终止条件
{
res.push_back(path); //存放符合题目结果
return; //返回
}
for(选择 in 选择列表 )
{
做选择
backtrace(路径,选择列表) //递归算法,类似dfs
撤销选择,回溯
}
首先,定义一个全局二维向量vector<vector>res 用来存放结果。其次定义一维向量,符合res的路径的结果,vector path。设定row为行,代表的是走向了棋盘的第几行了。
题目的条件:
1.不同行
2.不同列
3.不同斜线(45度角和135度角)
因此,递归终止条件可以写:
if(row == n)
{
res.push_back(path);
return;
}
有了判断递归终止条件,之后就是在棋盘中判断每行处理的逻辑。
每一行都有row,接下来就是每一列col。可以用for循环通过col遍历整个棋盘,这样就做到了棋盘上每个位置都会遍历到。
for(int col = 0; col < n; col++)
{
//判断此处位置是否符合放置皇后的三个条件(不同行,不同列,不同斜线)
if(help(n,row,col,path))
{
path[row][col] = 'Q'; //设定皇后位置
backtrace(n, row + 1, path); //深层搜索,dfs,递归处理
path[row][col] = '.'; //撤销设定皇后选择,回溯
}
}
连起来写就是:
void backtrace(int n, int row,vector<string> &path)
{
if(row == n)
{
res.push_back(path);
return;
}
for(int col = 0; col < n; col++)
{
//判断此处位置是否符合放置皇后的三个条件(不同行,不同列,不同斜线)
if(help(n,row,col,path))
{
path[row][col] = 'Q'; //设定皇后位置
backtrace(n, row + 1, path); //深层搜索,dfs,递归处理
path[row][col] = '.'; //撤销设定皇后选择,回溯
}
}
}
最后写下判断放置皇后,符合题目要求的三个条件(不同行,不同列,不同斜线),行row就不用判断了,因为行row会递增,判断列col和45度角斜线和135度角斜线。
bool help(int n, int row, int col, vector<string> path)
{
//判断列,判断该行所在的列,也就是棋盘上 上面列的部分没有皇后,下面row还没到达,一般不用管。
for(int i = 0; i < row; i++)
{
if(path[i][col] == 'Q')
{
return false;
}
}
// 判断斜线45度角,45斜线是右上角向上走,因此行i就是变小,列j变大。
for(int i = row - 1, j = col + 1; i >=0 && j < n; i--, j++)
{
if(path[i][j] == 'Q')
{
return false;
}
}
// 判断斜线135度角,135斜线左上角向上走,因此行i就是变小,列j变大。
for(int i = row - 1, j = col - 1; i >= 0 && j >=0; i--, j--)
{
if(path[i][j] == 'Q')
{
return false;
}
}
//判断无误后,返回正确
return true;
}
完整版代码:
class Solution {
public:
vector<vector<string>> res;
vector<vector<string>> solveNQueens(int n) {
vector<string> path(n, string(n, '.'));
backtrace(n, 0, path);
return res;
}
void backtrace(int n, int row, vector<string> &path)
{
if(row == n)
{
res.push_back(path);
return;
}
for (int col = 0; col < n; col++)
{
if(help(n, row, col, path))
{
path[row][col] = 'Q';
backtrace(n, row + 1, path);
path[row][col] = '.';
}
}
}
bool help(int n, int row, int col, vector<string> &path)
{
for(int i = 0; i < row; i++)
{
if(path[i][col] == 'Q')
{
return false;
}
}
for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
{
if(path[i][j] == 'Q')
{
return false;
}
}
for(int i = row - 1, j = col - 1; i >= 0 && j >=0; i--, j--)
{
if(path[i][j] == 'Q')
{
return false;
}
}
return true;
}
};