这就是传说中的N皇后? 回溯算法安排!| LeetCode:51.N皇后_哔哩哔哩_bilibili
// 时间复杂度O(n^2)
// 空间复杂度O(n^2)class Solution {List<List<String>> res = new ArrayList<>();public List<List<String>> solveNQueens(int n) {// 构建棋盘char[][] chessboard = new char[n][n];// 逐行填充for(char[] c: chessboard)Arrays.fill(c, '.');backtracking(n, 0, chessboard);return res;}public void backtracking(int n, int row, char[][] chessboard){if(row == n){res.add(ArrayToList(chessboard));return;}for(int col = 0; col<n; col++){if(isValid(row, col, n, chessboard)){chessboard[row][col] = 'Q';backtracking(n, row+1, chessboard);chessboard[row][col] = '.';}}return;}public List<String> ArrayToList(char[][] chessboard){List<String> list = new ArrayList<>();for(char[] c: chessboard){list.add(String.copyValueOf(c)); // 将二维数组每一行作为一个字符串存储进入列表,一个二维数组就变成一行若干的字符串}return list;}public boolean isValid(int row, int col, int n, char[][] chessboard){// 检查之前已经填充了Q的行是否在当前col列中放置的Qfor(int i=0; i<row; i++){if(chessboard[i][col] == 'Q')return false;}// 检查之前已经完成Q填充的行的45度是否与当前重复for(int i=row-1, j=col-1; i>=0&&j>=0; j--,i--){if(chessboard[i][j] == 'Q')return false;}for(int i=row-1, j=col+1; i>=0&&j<=n-1; i--,j++){if(chessboard[i][j] == 'Q')return false;}return true;}
}