Is the follow-up of the previous question. There are several methods in total. It is easy to use global variables, but in java, primitive parameters cannot be easily passed by reference or pointer as C ++. So I think it is better to use return value to record the number of methods!
Package Level4; import java. util. arrayList;/*** N-Queens II ** Follow up for N-Queens problem. ** Now, instead outputting board configurations, return the total number of * distinct solutions. ** http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png **/public class S52 {public static void main (String [] args) {System. out. println (totalNQueens (8);} public static int totalNQueens (int n) {int [] queenList = new int [n]; return placeQueen (queenList, 0, n );} // recursively backtrack the eight queens. The key record is the public static int placeQueen (int [] queenList, int row, int n) {// Base Case, if (row = n) {return 1;} int cnt = 0; // start searching for this row // traverse all columns in the row, test which location is safe for (int col = 0; col <n; col ++) {if (isSafe (queenList, row, col )) {queenList [row] = col; cnt + = placeQueen (queenList, row + 1, n) ;}} return cnt ;}// determine whether the coordinates are (row, col) is safe (check rows, columns, positive and negative diagonal lines) // stores rows and column coordinates pair in the queenList, that is, queenList [row] = col public static boolean isSafe (int [] queenList, int row, int col) {for (int preRow = 0; preRow <row; preRow ++) {int preCol = queenList [preRow]; if (preRow = row) {// theoretically no check is required, because preRow is always less than the return false of row ;} if (preCol = col) {// check whether return false is in the same column;} if (row-preRow = col-preCol) {// return false on the diagonal line ;} if (preRow + preCol = row + col) {// return false on the diagonal line;} return true ;}}