Best Solution With Java 1ms Work 100%


  • 0
    Y

    My Solution Work 100% passes All Test Cases:

    public int totalNQueens(int n) {
        boolean []arr = new boolean[n];
        boolean []d1 = new boolean[2*n];
        boolean []d2 = new boolean[2*n]; 
        
        int res = dfs(0 , arr , d1 , d2 , n);
        
        return res;
    }
    
    public int dfs(int row, boolean arr[] , boolean[] d1 , boolean[] d2 , int n ){
        if(row == n)
            return 1;
        int res = 0;
        for(int col=0 ; col < n ; col++){
            if(!arr[col] && !d1[row+col+1] && !d2[row+(n - 1 - col)+1]){
                arr[col] = true;
                d1[row+col+1] = true;
                d2[row+(n - 1 - col)+1] = true;
                res += dfs(row+1 , arr , d1 , d2 , n);
                arr[col] = false;
                d1[row+col+1] = false;
                d2[row+(n - 1 - col)+1] = false;
            }
        }
        return res;
    }

Log in to reply
 

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