class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> result=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]='.'; } } dfs(0,n,board,result); return result; } private void dfs(int i,int n,char[][] board,List<List<String>> result){ if(i==n){ //generate answer List<String> path=new ArrayList<>(); for(int x=0;x<n;x++){ StringBuilder sb=new StringBuilder(); for(int y=0;y<n;y++){ sb.append(board[x][y]); } path.add(sb.toString()); } result.add(new ArrayList<>(path)); return; } for(int j=0;j<n;j++){ if(inRightPlace(i, j, board)){ board[i][j]='Q'; dfs(i+1,n,board,result); board[i][j]='.'; } } } private boolean inRightPlace(int i,int j,char[][] board){ //row for(int y=0;y<board.length;y++){ if(board[i][y]=='Q') return false; } //col for(int x=0;x<board.length;x++){ if(board[x][j]=='Q') return false; } //k=1 for(int x=0;x<board.length;x++){ int y=x-i+j; if(y<board.length&&y>=0&&board[x][y]=='Q') return false; } //k=-1 for(int x=0;x<board.length;x++){ int y=i+j-x; if(y<board.length&&y>=0&&board[x][y]=='Q') return false; } return true; }}