import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
<p>按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。</p>
<p><strong>n 皇后问题</strong> 研究的是如何将 <code>n</code> 个皇后放置在 <code>n×n</code> 的棋盘上,并且使皇后彼此之间不能相互攻击。</p>
<p>给你一个整数 <code>n</code> ,返回所有不同的 <strong>n<em> </em>皇后问题</strong> 的解决方案。</p>
<div class="original__bRMd">
<div>
<p>每一种解法包含一个不同的 <strong>n 皇后问题</strong> 的棋子放置方案,该方案中 <code>'Q'</code> 和 <code>'.'</code> 分别代表了皇后和空位。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" style="width: 600px; height: 268px;" />
<pre>
<strong>输入:</strong>n = 4
<strong>输出:</strong>[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
<strong>解释:</strong>如上图所示,4 皇后问题存在两个不同的解法。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>n = 1
<strong>输出:</strong>[["Q"]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
</ul>
</div>
</div>
<div><div>Related Topics</div><div><li>数组</li><li>回溯</li></div></div><br><div><li>👍 1386</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
/**
*
* 回溯
*/
List<List<String>> res = new LinkedList<>();
public List<List<String>> solveNQueens(int n) {
char[][] board = new char[n][n];
//要初始化
for (char[] c : board) {
Arrays.fill(c, '.');
}
backtrack(board, 0);
return res;
}
void backtrack(char[][] board, int row) {
if (board.length == row) {
res.add(charToList(board));
return;
}
int n = board[row].length;
for (int i = 0; i < n; i++) {
if (!isValid(board, row, i)) {
continue;
}
board[row][i] = 'Q';
backtrack(board, row + 1);
board[row][i] = '.';
}
}
/* 判断是否可以在 board[row][col] 放置皇后 */
public boolean isValid(char[][] board, int row, int col) {
int n = board.length;
// 检查列是否有皇后冲突
for (int i = 0; i < n; i++) {
if (board[i][col] == 'Q') {
return false;
}
}
// 检查右上方是否有皇后冲突
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q') {
return false;
}
}
// 检查左上方是否有皇后冲突
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
return true;
}
public List charToList(char[][] board) {
List<String> list = new ArrayList<>();
for (char[] c : board) {
list.add(String.copyValueOf(c));
}
return list;
}
}
//leetcode submit region end(Prohibit modification and deletion)
leetcode51-n皇后
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.