class Solution { public static int[] x; public static int sum=0; public static char[][] board; public List<List<String>> solveNQueens(int n) { x =new int[n]; for(int i=0;i<n;i++){ x[i]=0; } board = new char[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++) { board[i][j] = '.'; } } List<List<String>> res = new ArrayList<List<String>>(); BackTrack(0,board,res,n); return res; } public static void BackTrack( int k ,char[][] board,List<List<String>> res,int n){ if(k==n){ res.add(construct(board,n)); return; } for(int i=0;i<n;i++){ x[k] = i; if(isValid(k)){ board[k][x[k]] = 'Q'; BackTrack(k+1,board,res,n); } board[k][x[k]] = '.'; } } public static boolean isValid(int t){ for(int j=0;j<t;j++){ if( Math.abs(j-t) == Math.abs(x[j] -x[t]) || x[j] == x[t] ) return false; } return true; } public static List<String> construct(char[][] board,int n){ List<String> res = new LinkedList<String>(); for(int i=0;i<n;i++){ String s = new String(board[i]); res.add(s); } return res; } }