class Solution { List<List<String>> res; //检查 列+主对角+负对角 boolean[] cols; boolean[] poss; boolean[] negs; char[][] t; int m ; public List<List<String>> solveNQueens(int n) { //初始化 m = n; t = new char[n][n]; for (char[] c : t) { Arrays.fill(c, '.'); } res = new ArrayList<>(); cols = new boolean[n]; poss = new boolean[2*n-1]; negs = new boolean[2*n-1]; backtrace(0); return res; } //需要什么参数呢? private void backtrace(int r){ //赢了 添加结果 //语义应该是到了n+1了 if(r == m){ List<String> winner = transform(); res.add(winner); return ; } //同层横向走 for(int i = 0;i<m;i++){ if(isValid(r,i)){ //当前可以行 t[r][i] = 'Q'; cols[i] = true; poss[r+i] = true; negs[r-i+m-1] = true; backtrace(r+1); t[r][i] = '.'; cols[i] = false; poss[r+i] = false; negs[r-i+m-1] = false; } } } private boolean isValid(int r,int c){ if(cols[c] ) return false; if(poss[r+c]) return false; if(negs[r-c+m-1]) return false; return true; } private List<String> transform(){ List<String> res = new ArrayList<>(); for(char[] e:t){ res.add(new String(e)); } return res; } }