LeetCode51-20.9.3-N皇后

tech2024-08-07  53

链接:LeetCode51 过程:略 思路:枚举回溯 代码:

class Solution { List<List<String>> ans=new ArrayList<>(); List<String> temp=new ArrayList<>(); boolean[][] fail=null; int n; public List<List<String>> solveNQueens(int n) { fail=new boolean[n][n]; this.n=n; dfs(0); return ans; } public void dfs(int k){ if(k==n){ ans.add(new ArrayList<>(temp)); return; } StringBuilder sb=new StringBuilder(); boolean[][] fail2=new boolean[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ fail2[i][j]=fail[i][j]; } } for(int i=0;i<n;i++){ if(!fail[k][i]){ sb.append('Q'); for(int j=i+1;j<n;j++)sb.append('.'); temp.add(sb.toString()); for(int row=k+1;row<n;row++)fail[row][i]=true; for(int row=k+1,col=i+1;row<n&&col<n;row++,col++)fail[row][col]=true; for(int row=k+1,col=i-1;row<n&&col>=0;row++,col--)fail[row][col]=true; dfs(k+1); for(int row=0;row<n;row++){ for(int col=0;col<n;col++){ fail[row][col]=fail2[row][col]; } } sb.delete(i,n); temp.remove(k); } sb.append('.'); } } }
最新回复(0)