Simple Java code


  • 0
    T

    public class Solution {
    int result=0;
    public int totalNQueens(int n) {
    boolean[] varital = new boolean[n];
    boolean[] leftfall = new boolean[2n];
    boolean[] rightfall = new boolean[2
    n];
    totalNQueuesHelper(0,n,varital,leftfall,rightfall);
    return result;
    }

    public void totalNQueuesHelper(int row,int n,boolean[] varital,boolean[] leftfall,boolean[] rightfall){
    if(row == n){
    result++;
    return;
    }
    for(int col=0; col<n; ++col){
    if(!varital[col] && !leftfall[row-col+n] && !rightfall[row+col]){
    //The origin of row-col + n is mainly due to 45 ° in the coordinates that y = x then y - x = 0, //the resulting, plus n is to prevent row-col is negative.
    varital[col] = leftfall[row-col+n] = rightfall[row+col] = true;
    totalNQueuesHelper(row+1,n,varital,leftfall,rightfall);
    varital[col] = leftfall[row-col+n] = rightfall[row+col] = false;
    }
    }
    }


Log in to reply
 

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