leetcode 51——N皇后
题目描述:
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q…", // 解法 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // 解法 2
“Q…”,
“…Q”,
“.Q…”]
]
解释: 4 皇后问题存在两个不同的解法。
提交:递归
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
char** ch = new char* [n];
for (int i = 0; i < n; ++i)
{
*(ch + i) = new char[n];
for (int j = 0; j < n; ++j)
{
ch[i][j] = '.';
}
}
queenToChess(ch, 0, n);
return ans;
}
bool Danger(char** ch, int row, int col, int n) //判断(row,col)位置是否危险,即是否可以放皇后
{
for (int i = 0; i < n; ++i) //判断列方向是否有皇后
{
if (ch[i][col] == 'Q') return true;
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) //往(row,col)的左上角判断
{
if (ch[i][j] == 'Q') return true;
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j)//往(row,col)的右上角判断
{
if (ch[i][j] == 'Q') return true;
}
return false; //表明(row,col)无危险,可以放皇后
}
void queenToChess(char** ch, int row, int n) //将n个皇后放到n*n的象棋盘上
{
if (row >= n)
{//当完成一种放皇后的方案后执行的操作
for (int i = 0; i < n; ++i)
{
string str;
for (int j = 0; j < n; ++j)
{
str += ch[i][j];
}
chess.push_back(str);
}
ans.push_back(chess);
chess.clear(); //将chess内容插入到ans后,chess需要清空。
return; //结束
}
for (int col = 0; col < n; ++col)
{
if (!Danger(ch, row, col, n)) //(row,col)不危险,可以放皇后
{
ch[row][col] = 'Q'; //将皇后放到该位置
queenToChess(ch, row + 1, n);
ch[row][col] = '.'; //后序过程走不动了,回退到这里,这是应将应将原来的皇后拿走。
}
}
}
private:
vector<vector<string>> ans;
vector<string> chess;
};