n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,而且使皇后彼此之间不能相互攻击。java
上图为 8 皇后问题的一种解法。this
给定一个整数 n,返回全部不一样的 n 皇后问题的解决方案。code
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别表明了皇后和空位。blog
示例:io
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],class
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不一样的解法。sed
class Solution { private List<List<String>> solutions; private char[][] nQueens; private boolean[] colUsed; private boolean[] diagonals45Used; private boolean[] diagonals135Used; private int n; public List<List<String>> solveNQueens(int n) { solutions = new ArrayList<>(); nQueens = new char[n][n]; for (int i = 0; i < n; i ++){ Arrays.fill(nQueens[i],'.'); } colUsed = new boolean[n]; diagonals45Used = new boolean[2 * n - 1]; diagonals135Used = new boolean[2 * n - 1]; this.n = n; dfs(0); return solutions; } private void dfs(int row){ if (row == n){ List<String> list = new ArrayList<>(); for (char[] chars : nQueens){ list.add(new String(chars)); } solutions.add(list); return; } for (int col = 0; col < n; col++){ int diagonals45Idx = row + col; int diagonals135Idx = n - 1 - (row -col); if (colUsed[col] || diagonals45Used[diagonals45Idx] || diagonals135Used[diagonals135Idx]){ continue; } nQueens[row][col] = 'Q'; colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = true; dfs(row + 1); colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = false; nQueens[row][col] = '.'; } } }