1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| class Solution { List<List<String>> res = new ArrayList<>(); public List<List<String>> solveNQueens(int n) { List<String> board = new ArrayList<>(); for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < n; j++) { sb.append("."); } board.add(sb.toString()); }
backtrack(board, 0); return res; }
public void backtrack(List<String> board, int row) { if (row == board.size()) { res.add(new ArrayList<>(board)); return; }
for (int cel = 0; cel < board.size(); cel++) { if (!isValid(board, row, cel)) { continue; }
board.set(row, board.get(row).substring(0, cel) + 'Q' + board.get(row).substring(cel + 1)); backtrack(board, row + 1); board.set(row, board.get(row).substring(0, cel) + '.' + board.get(row).substring(cel + 1)); } }
public boolean isValid(List<String> board, int row, int cel) { for (int i = row - 1; i >= 0; i--) { if (board.get(i).charAt(cel) == 'Q') { return false; } }
for (int i = row - 1, j = cel - 1; i >= 0 && j >= 0; i--, j--) { if (board.get(i).charAt(j) == 'Q') { return false; } }
for (int i = row - 1, j = cel + 1; i >= 0 && j < board.size(); i--, j++) { if (board.get(i).charAt(j) == 'Q') { return false; } }
return true; } }
|