Skip to content

Instantly share code, notes, and snippets.

@Rabierre
Last active May 27, 2019 05:56
Show Gist options
  • Save Rabierre/bdb258337ce2e21aed94b79762566273 to your computer and use it in GitHub Desktop.
Save Rabierre/bdb258337ce2e21aed94b79762566273 to your computer and use it in GitHub Desktop.
class NQueens {
public int totalNQueens(int n) {
int[] B = new int[n];
return nqueens(B, 0);
}
public int nqueens(int[] B, int row) {
if (row == B.length) return 1;
int count = 0;
for (int j=0; j<B.length; j++) {
if (!check(B, row, j)) continue;
B[row] = j;
count += nqueens(B, row+1);
}
return count;
}
public boolean check(int[] B, int row, int col) {
for (int i=0; i < row; i++) {
// check same column
if (B[i] == col) return false;
// check diagonal
if ((row + col == B[i] + i) || (row - col == i - B[i]))
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment