LeetCode-52.N-Queen II

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.."]
]
使用深度优先遍历,并剪枝
注意斜线上的规律,左斜线上的点 横纵坐标和相同,右斜线上的点 横纵坐标差相同
 1 class Solution {
 2     int total = 0;
 3     public int totalNQueens(int n) {
 4         
 5         dfs(n,0,new ArrayList<Integer>(),new ArrayList<Integer>(),new ArrayList<Integer>());
 6         return total;
 7     }
 8     private void dfs( int n, int level, List<Integer> cols, List<Integer> sum, List<Integer> dif) {
 9         if (level == n) {
10             total++;
11             return;
12         }
13         for (int i = 0; i < n; i++) {
14             if (cols.contains(i) || sum.contains(i + level) || dif.contains(i - level))
15                 continue;
16             cols.add(i);
17             sum.add(i + level);
18             dif.add(i - level);
19             dfs(n, level + 1, cols, sum, dif);
20             cols.remove(cols.size() - 1);
21             sum.remove(sum.size() - 1);
22             dif.remove(dif.size() - 1);
23         }
24     }
25 }

 

使用位运算(最优解)

 1 class Solution {//DFS 位运算 mytip
 2     public int totalNQueens(int n) {
 3         int total=0;
 4         return dfs(total,n,0,0,0,0);
 5         //return total;
 6     }
 7     private int dfs(int total, int n, int level, int cols, int pie, int na) {
 8         if (level == n) {
 9             total++;
10             return total;
11         }
12         int bits = (~(cols|pie|na))&((1<<n)-1);//得到可能放的空位
13         while(0!=bits){//遍历可能放的空位
14             int cur = bits&(-bits);//得到最后一个1
15             total= dfs(total,n,level+1,cols|cur,(pie|cur)<<1,(na|cur)>>1);
16             bits= bits&(bits-1);//清楚最后一个1
17         }
18         return total;
19     }
20 }

 

相关题

n皇后 LeetCode51 https://www.cnblogs.com/zhacai/p/10621300.html



转载于:https://www.cnblogs.com/zhacai/p/10621381.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值