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] = '.'; } } }