程序媛詹妮弗
终身学习

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

 

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

 

题意:

 

code

 1 class Solution {
 2    private int count; // 解的个数
 3     // 这三个变量用于剪枝
 4     private boolean[] columns;   // 表示已经放置的皇后占据了哪些列
 5     private boolean[] main_diag; // 占据了哪些主对角线
 6     private boolean[] anti_diag; // 占据了哪些副对角线
 7 
 8 
 9     public int totalNQueens(int n) {
10         this.count = 0;
11         this.columns = new boolean[n];
12         this.main_diag = new boolean[2 * n - 1];
13         this.anti_diag = new boolean[2 * n - 1];
14 
15         int[] C = new int[n]; // C[i]表示第i行皇后所在的列编号
16         dfs(C, 0);
17         return this.count;
18     }
19 
20     void dfs(int[] C, int row) {
21         final int N = C.length;
22         if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
23             ++this.count;
24             return;
25         }
26 
27         for (int j = 0; j < N; ++j) {  // 扩展状态,一列一列的试
28             final boolean ok = !columns[j] &&
29                     !main_diag[row - j + N - 1] &&
30                     !anti_diag[row + j];
31             if (!ok) continue;  // 剪枝:如果合法,继续递归
32             // 执行扩展动作
33             C[row] = j;
34             columns[j] = main_diag[row - j + N - 1] =
35                     anti_diag[row + j] = true;
36             dfs(C, row + 1);
37             // 撤销动作
38             // C[row] = -1;
39             columns[j] = main_diag[row - j + N - 1] =
40                     anti_diag[row + j] = false;
41         }
42     }
43 }

 

posted on 2018-10-18 14:28  程序媛詹妮弗  阅读(173)  评论(0编辑  收藏  举报