首页 > 其他 > 详细

N-Queens II 解答

时间:2015-10-18 06:40:06      阅读:283      评论:0      收藏:0      [点我收藏+]

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 }

 

N-Queens II 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4888816.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!