N皇后 【回溯算法】

51. N 皇后 - 力扣(LeetCode)

 

核心:1.按照层去选择 2.使用String.copyValueOf(char[] ) 将char数组转成String

class Solution {
    List<List<String>>  res;
    public List<List<String>> solveNQueens(int n) {
        res = new ArrayList<>();
        // 初始化棋盘
        char[][] board = new char[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                board[i][j] = '.';
            }
        }
        // 回溯
        traceBack(board,0);
        return res;
    }

    public void traceBack(char[][] board,int row){
        if(row == board.length){
            res.add(Array2List(board));
            return;
        }
        for(int col=0;col<board.length;col++){
            if(!isVaild(board,row,col)){
                continue;
            }
            // 选择
            board[row][col] = 'Q';
            // 下一层
            traceBack(board,row+1);
            // 撤销选择
            board[row][col] = '.';
        }
    }

    public boolean isVaild(char[][] board,int row,int col){
        // 1. 检查上方
        for(int i=0;i<row;i++){
            if(board[i][col] == 'Q') 
                return false;
        }
        // 2. 检查右上方
        for(int i=row-1,j=col+1;i>=0 && j<board.length;i--,j++){
            if(board[i][j] == 'Q')
                return false;
        }
        // 3. 检查左上方
        for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
            if(board[i][j] == 'Q')
                return false;
        }
        return true;
    }
    public List<String> Array2List(char[][] board){
        List<String> charList = new ArrayList<>();
        for(char[] c:board){
           charList.add(String.copyValueOf(c));
        }    
        return charList;
    }   
}

  

posted @ 2022-09-20 20:20  yky_xukai的胡思乱想  阅读(22)  评论(0)    收藏  举报