[leetcode]N-QueensII

N-Queens II

Follow up for N-Queens problem.

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

 

算法思路:

[leetcode]N-Queens完全一样,不过更简单,只统计个数即可。

代入如下:

 1 public class Solution {
 2     int count = 0;
 3     public int totalNQueens(int n) {
 4         if(n < 1) return 0;
 5         int[] hash = new int[n];
 6         dfs(hash,0,n);
 7         return count;
 8     }
 9     private void dfs(int[] hash,int row,int n){
10         if(row == n){
11             count++;
12             return;
13         }
14         for(int i = 0; i < n; i++){
15             if(!isConflict(hash,row,i)){
16                 hash[row] = i;
17                 dfs(hash, row + 1, n);
18                 hash[row] = 0;
19             }
20         }
21     }
22     private boolean isConflict(int[] hash,int row,int column){
23         for(int i = 0; i < row; i++){
24             if(hash[i] == column || i - hash[i] == row - column || i + hash[i] == row + column) return true;
25         }
26         return false;
27     }
28 }

 

posted on 2014-07-14 22:30  喵星人与汪星人  阅读(229)  评论(0编辑  收藏  举报