N-Queens II 解答

Question

Follow up for N-Queens problem.

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

Solution

This problem seems like 2D DP, but it is not.

For DP problem, usually we will have a/ some directions. But here, we can go to all four directions. So this can not be solved by DP.

We still use the way to implement N-Queens.

There is one stuff worth mentioning:

In java, if in function f(x), we pass a variable x of primitive data type like int into a function g(x), the value of x in f(x) is not changed.

If we want it to be modified, we need to pass a reference.

 1 public class Solution {
 2     
 3     public int totalNQueens(int n) {
 4         // Should use an object rather than a int variable here
 5         // We want "result" to be modified in helper function
 6         int[] result = {0};
 7         int[] queen = new int[n];
 8         helper(n, 0, queen, result);
 9         return result[0];
10     }
11     
12     private void helper(int n, int rowNum, int[] queen, int[] result) {
13         if (n == rowNum) {
14             result[0]++;
15             return;
16         }
17         
18         for (int i = 0; i < n; i++) {
19             queen[rowNum] = i;
20             if (check(rowNum, queen))
21                 helper(n, rowNum + 1, queen, result);
22         }
23     }
24     
25     private boolean check(int rowNum, int[] queen) {
26         int colNum = queen[rowNum];
27         for (int i = 0; i < rowNum; i++) {
28             if ((colNum == queen[i]) || (queen[i] - i == colNum - rowNum) || (queen[i] + i == colNum + rowNum))
29                 return false;
30         }
31         return true;
32     }
33 }

 

posted @ 2015-10-18 04:09  树獭君  阅读(171)  评论(0编辑  收藏  举报