N-Queens II

image.png

image.png

class Solution {
    public int totalNQueens(int n) {
        int[][] matrix = new int[n][n];
        int[] hashPath1 = new int[n];
        int[] hashPath2 = new int[2*n -1];
        int[] hashPath3 = new int[2*n -1];
        return queens(0,n,matrix, hashPath1, hashPath2, hashPath3);
    }

    int queens(int col, int n, int[][] matrix, int[] hashPath1, int[] hashPath2, int[] hashPath3){
        if(col == n){
            return 1;
        }

        int count = 0;
        for(int row = 0; row < n; row++){
            if(isAllowed2(row, col, matrix, hashPath1, hashPath2, hashPath3)){
                hashPath1[row] = 1;
                hashPath2[row + col] = 1;
                hashPath3[n-1 + row - col] = 1;

                matrix[row][col] = 1;
                count += queens(col+1, n, matrix, hashPath1, hashPath2, hashPath3);
                matrix[row][col] = 0;   

                hashPath1[row] = 0;
                hashPath2[row + col] = 0;
                hashPath3[n-1 + row - col] = 0;
            }
        }
        return count;
    }


    boolean isAllowed2(int row, int col, int[][] mat, int[] hashPath1, int[] hashPath2, int[] hashPath3){
        if(hashPath1[row] == 1 || hashPath2[row+col] == 1 || hashPath3[mat[0].length - 1 + row - col] == 1) 
            return false;
        return true;
    }

    boolean isAllowed(int row, int col, int[][] mat){
        for(int i = row, j = col; i >= 0 && j >=0; i--,j--){
            if(mat[i][j] == 1) return false;
        }
        for(int i = row, j = col; i >= 0 && j >=0; j--){
            if(mat[i][j] == 1) return false;
        }
        for(int i = row, j = col; i < mat[0].length && j >=0; i++,j--){
            if(mat[i][j] == 1) return false;
        }
        return true;
    }
}

image.png