[LC] 51. N-Queens
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
Input: 4 Output: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<>(); List<String> list = new ArrayList<>(); if (n == 0) { return res; } helper(res, list, 0, n); return res; } private void helper(List<List<String>> res, List<String> list, int level, int n) { if (level == n) { res.add(new ArrayList<>(list)); return; } char[] charArr = new char[n]; Arrays.fill(charArr, '.'); for (int i = 0; i < n; i++) { charArr[i] = 'Q'; if (isValid(i, list)) { list.add(new String(charArr)); helper(res, list, level + 1, n); list.remove(list.size() - 1); } charArr[i] = '.'; } } private boolean isValid(int column, List<String> list) { int row = list.size(); for (int i = 0; i < row; i++) { String cur = list.get(i); int col = cur.indexOf("Q"); if (col == column || row - i == Math.abs(col - column)) { return false; } } return true; } }