My Easy Understand Java Solution


  • 2
    A
    public class Solution {
    
    private final Set<Integer> cols = new HashSet<Integer>();
    private final Set<Integer> diag1s = new HashSet<Integer>();
    private final Set<Integer> diag2s = new HashSet<Integer>();
    List<List<String>> re = new ArrayList<List<String>>();
    public List<List<String>> solveNQueens(int n) {
        int[][] s = new int[n][n];
        helper(0,n,s);
        return re;
    }
    
    private void helper(int row,int n,int[][] s){
        for(int col=0;col<n;col++){
            if(cols.contains(col))
                continue;
            int diag1 = row+col;
            if(diag1s.contains(diag1))
                continue;
            int diag2 = row-col;
            if(diag2s.contains(diag2))
                continue;
            if(row==n-1){
                s[row][col] = 1;
                re.add(convertToList(s,n));
                s[row][col] = 0;
            }else{
                cols.add(col);
                diag1s.add(diag1);
                diag2s.add(diag2);
                s[row][col] = 1;
                helper(row+1,n,s);
                s[row][col] = 0;
                cols.remove(col);
                diag1s.remove(diag1);
                diag2s.remove(diag2);
            }
        }
        
    }
    
    private List<String> convertToList(int[][] s,int n){
        List<String> solution = new ArrayList<String>();
        for(int i=0;i<n;i++){
            StringBuilder line = new StringBuilder();
            for(int j=0;j<n;j++){
                if(s[i][j]==0){
                    line.append(".");
                }else{
                    line.append("Q");
                }
            }
            solution.add(line.toString());
        }
        return solution;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.