Question
Follow up for n-queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Method
Like the above method, the backtracking method is used, and the structure is basically the same. Only the number of returned results is required.
public int totalNQueens(int n) { int[] queenAtCol = new int[n]; int total = getNQueens(0, n, queenAtCol); return total; } public List<String[]> solveNQueens(int n) { List <String[]> list = new ArrayList<String[]>(); return list; }private int getNQueens(int row, int n, int[] queenAtCol) {if (row == n) {return 1;} else {int tempSum = 0;for (int col = 0; col < n; col++) {if (isValid(row,col,queenAtCol)) {queenAtCol[row] = col;tempSum += getNQueens(row + 1, n, queenAtCol);}}return tempSum;}}private boolean isValid(int row, int col,int[] queenAtCol) {//row is valid.//column for (int i = 0; i < row; i++) {if (queenAtCol[i] == col) {return false;}}for (int i = 0; i < row; i++) {if (i + queenAtCol[i] == row + col) {return false;}}for (int i = 0; i < row; i++) {if (col - row == queenAtCol[i] - i) {return false;}}return true;}