LeetCode 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;  
 3     int[] A; 
 4     public int totalNQueens(int n) {
 5         A = new int[n];  
 6         nqueens(0, n);  
 7         return result;    
 8     }
 9 
10      public void nqueens(int cur, int n){  
11          if(cur==n) result++;  
12          else {  
13              for(int i=0;i<n;i++){  
14                  A[cur] = i;  
15                  if(valid(cur)){  
16                      nqueens(cur+1, n);  
17                  }  
18              }  
19          }  
20      }  
21      public boolean valid(int r){  
22          for(int i=0;i<r;i++){  
23              if(A[i]==A[r]|| Math.abs(A[i]-A[r])==r-i){  
24                  return false;  
25              }  
26          }  
27          return true;  
28      }  
29 }

 

posted @ 2015-01-23 22:05  birdhack  阅读(131)  评论(0编辑  收藏  举报