Another accepted Java solution...


  • 0
    P
    public class Solution {
        public int totalNQueens(int n) {
            int row = 0;
            int count = 0;
            int[] taken = new int[n];
            Arrays.fill(taken, -1);
            return helper(taken, row, count);
        }
        
        private int helper(int[] taken, int row, int count){
            if(row == taken.length){
                count ++;
            }else{
                for(int col = 0; col < taken.length; col ++){
                    if(valid(taken, row, col)){
                        taken[col] = row;
                        count = helper(taken, row + 1, count);
                        taken[col] = -1;
                    }
                }
            }
            return count;
        }
        
        private boolean valid(int[] taken, int row, int col){
            if(taken[col] != -1){
                return false;
            }
            int c1 = 0;
            int c2 = 0;
            for(int r = row - 1; r >= 0 ; r --){
                c1 ++;
                c2 --;
                if(col + c1 < taken.length && taken[col + c1] == r || col + c2 >= 0 && taken[col + c2] == r){
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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