N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

 1 public class Solution {
 2     int result = 0;
 3     public int totalNQueens(int n) {
 4         // Start typing your Java solution below
 5         // DO NOT write main() function
 6         result = 0;
 7         solve(new int[n], 0);
 8         return result;
 9     }
10     public void solve(int[] arr, int pos){
11         int size = arr.length;
12         if(pos == size){
13             result ++;
14             return;
15         }
16         for(int i = 0; i < size; i ++)
17             if(isValid(arr, pos, i)){
18                 arr[pos] = i;
19                 solve(arr, pos + 1);    
20             } 
21     }
22     public boolean isValid(int[] arr, int pos, int check){
23         for(int i = 0; i < pos; i ++)
24             if(check == arr[i] || Math.abs(pos - i) == Math.abs(check - arr[i])) return false;
25         return true;
26     }
27 }

 

posted on 2014-01-08 05:43  Step-BY-Step  阅读(176)  评论(0编辑  收藏  举报

导航