Last active
May 27, 2019 05:56
-
-
Save Rabierre/bdb258337ce2e21aed94b79762566273 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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