Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

 1         public static int NQueenII(int n)
 2         {
 3             int[] map = new int[n];
 4             int ret = NQueenIIHelper(map, n, 0);
 5             return ret;
 6         }
 7 
 8         public static int NQueenIIHelper(int[] map, int n, int row)
 9         {
10             if (row >= n || n == 1)
11             {
12                 return 1;
13             }
14 
15             int sum = 0;
16 
17             for (int i = 0; i < n; i++)
18             {
19                 bool valid = true;
20                 for (int j = 0; j < row; j++)
21                 {
22                     if (i == map[j] || Math.Abs(i - map[j]) == row - j)
23                     {
24                         valid = false;
25                         break;
26                     }
27                 }
28                 if (valid)
29                 {
30                     map[row] = i;
31                     sum += NQueenIIHelper(map, n, row + 1);
32                 }
33             }
34 
35             return sum;
36         }

代码分析:

  N-queen的延伸,好像更简单。一样的递归。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2021-05-22
  • 2021-06-04
  • 2022-02-16
  • 2021-05-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案