思考
1.对于回溯算法,和之前的生成括号是一样的,不要想着自己用for循环去解决这个问题,而是需要用递归解决。
2.要注意到的是,在递归时,不要用java的list这种传递,最好用int[][]类型属性来传递。
3.这一题有个限制条件,①皇后数目(当最后一个棋子已经下完)②横竖,斜线,这个斜线有点恶心的地方是是45°和135°都要考虑。
//n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
//
//
//
// 上图为 8 皇后问题的一种解法。
//
// 给定一个整数 n,返回 n 皇后不同的解决方案的数量。
//
// 示例:
//
// 输入: 4
//输出: 2
//解释: 4 皇后问题存在如下两个不同的解法。
//[
// [".Q..", // 解法 1
// "...Q",
// "Q...",
// "..Q."],
//
// ["..Q.", // 解法 2
// "Q...",
// "...Q",
// ".Q.."]
//]
//
//
//
//
// 提示:
//
//
// 皇后,是国际象棋中的棋子,意味着国王的妻子。皇后只做一件事,那就是“吃子”。当她遇见可以吃的棋子时,就迅速冲上去吃掉棋子。当然,她横、竖、斜都可走一或 N
//-1 步,可进可退。(引用自 百度百科 - 皇后 )
//
// Related Topics 回溯算法
// 👍 181 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int total = 0;
public int totalNQueens(int n) {
char[][] array = new char[n][n];
build(0, 0, n, array, '.', 0);
build(0, 0, n, array, 'Q', 1);
return total;
}
public void build(int x, int y, int n, char[][] oneResult, char currentCh, int queueCount) {
if (x >= n || y >= n) {
return;
}
if (currentCh == 'Q') {
// // 右下方斜线
int tempY = y - 1;
int tempX = x - 1;
while (tempX >= 0 && tempY >= 0) {
if (oneResult[tempX][tempY] == currentCh) {
return;
}
tempY--;
tempX--;
}
// 左上方斜线
tempX = x - 1;
tempY = y + 1;
while (tempX <= n - 1 && tempY >= 0 && tempX >= 0 && tempY <= n - 1) {
if (oneResult[tempX][tempY] == currentCh) {
return;
}
tempX--;
tempY++;
}
// 横线
for (int p = 0; p < y; p++) {
if (oneResult[x][p] == currentCh) {
return;
}
}
// 竖线
for (int p = 0; p < x; p++) {
if (oneResult[p][y] == currentCh) {
return;
}
}
}
oneResult[x][y] = currentCh;
if (x == n - 1 && y == n - 1) {
if (queueCount == n) {
total+=1;
}
return;
}
if (y == n - 1) {
build(x + 1, 0, n, oneResult, 'Q', queueCount + 1);
build(x + 1, 0, n, oneResult, '.', queueCount);
} else {
build(x, y + 1, n, oneResult, 'Q', queueCount + 1);
build(x, y + 1, n, oneResult, '.', queueCount);
}
}
}
//leetcode submit region end(Prohibit modification and deletion)