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