N皇后问题

private int result = 0;
    
    public int totalNQueens(int n){
        int[] x = new int[n];
        queens(x,n,0);
        return result;
    }
    
    private void queens(int[] x,int n,int row){
        for(int i=0;i<n;i++){
            if(check(x,row,i)){
                x[row] = i;
                if(row==n-1){
                    result++;
                    x[row] = 0;
                    return;
                }
                queens(x, n, row+1);
                x[row] = 0;
            }
        }
    }
    
    private boolean check(int[] x,int row,int col){
        for(int i=0;i<row;i++){
            if(x[i]==col || x[i]+i==row+col || x[i]-i==col-row){
                return false;
            }
        }
        return true;
    }

 

posted @ 2020-08-06 14:16  helloworldmybokeyuan  阅读(79)  评论(0编辑  收藏  举报