首页 > 代码库 > N-Queens II

N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

public class Solution {
    public int totalNQueens(int n) {
        Integer[] columns=new Integer[n];
        return dfs(0,n,columns);
    }
    public int dfs(int row,int n,Integer[] columns){
        if(row==n){
            return 1;
        }
        int res=0;
        for(int col=0;col<n;col++){
            if(isValid(columns,row,col)){
                columns[row]=col;
                res+=dfs(row+1,n,columns);
            }
        }
        return res;
    }
    public boolean isValid(Integer[] columns,int row1,int col1){
        for(int row2=0;row2<row1;row2++){
            int col2=columns[row2];
            if(col2==col1) return false;
            
            int colDistance=Math.abs(col1-col2);
            int rowDistance=row1-row2;
            if(colDistance==rowDistance) return false;
        }
        return true;
    }
}