N-Queens II @LeetCode

2014-11-24 08:41:51 · 作者: · 浏览: 1
是上一题的follow-up,问有总共几种方法。用全局变量易得,但是在java中不能像C++那么方便地用引用或指针传primitive参数。所以我觉得用return value来记录方法数更好!
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. 
 *  
 * https://www.cppentry.com/upload_files/article/76/1_mgump__.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);  
    }  
  
    // 递归回溯8皇后,关键记录下到达了哪一行了  
    public static int placeQueen(int[] queenList, int row, int n){  
        // Base Case, 已经完成任务了  
        if(row == n){  
            return 1;  
        }  
          
        int cnt = 0;  
        // 开始这一行的查找  
        // 遍历第row行的所有列,测试哪一个位置是安全的  
        for(int col=0; col