1import java.util.*;2
3class Solution {4 public List<List<String>> solveNQueens(int n) {5 List<List<String>> res = new ArrayList<>();6 dfs(0, n, new int[n], new boolean[n], res);7 return res;8 }9
10 private void dfs(int r, int n, int[] cols, boolean[] used, List<List<String>> res) {11 if (r == n) {12 if (!clashes(cols, n)) res.add(build(cols, n));13 return;14 }15 for (int c = 0; c < n; c++) {16 if (used[c]) continue;17 18 cols[r] = c;19 used[c] = true;20 dfs(r + 1, n, cols, used, res);21 used[c] = false; 22 }23 }24
25 private boolean clashes(int[] cols, int n) {26 27 for (int i = 0; i < n; i++) {28 for (int j = i + 1; j < n; j++) {29 if (cols[i] == cols[j] || Math.abs(i - j) == Math.abs(cols[i] - cols[j])) {30 return true;31 }32 }33 }34 return false;35 }36
37 private List<String> build(int[] cols, int n) {38 List<String> board = new ArrayList<>();39 for (int r = 0; r < n; r++) {40 char[] row = new char[n];41 Arrays.fill(row, '.');42 row[cols[r]] = 'Q';43 board.add(new String(row));44 }45 return board;46 }47}