《LeetCode力扣练习》代码随想录——回溯算法(N皇后—Java)
刷题思路来源于 代码随想录
51. N 皇后
-
回溯
class Solution { private List<List<String>> result = new ArrayList<>(); private char[][] board; public List<List<String>> solveNQueens(int n) { board = new char[n][n]; for (char[] chs : board) { Arrays.fill(chs, '.'); } backtrack(0, n); return result; } private void backtrack(int row, int n) { if (row == n) { result.add(arrayToList()); return; } for (int i = 0; i < n; i++) { if (isValid(row, i, n)) { board[row][i] = 'Q'; backtrack(row + 1, n); board[row][i] = '.'; } } return; } private List<String> arrayToList() { List<String> result = new ArrayList<>(); for (char[] chs : board) { result.add(new String(chs)); } return result; } private boolean isValid(int row, int col, int n) { for (int i = 0; i < row; i++) { if (board[i][col] == 'Q') { return false; } } for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 'Q') { return false; } } for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (board[i][j] == 'Q') { return false; } } return true; } }