题目: Follow up for N-Queens problem.

  Now, instead outputting board configurations, return the total number of distinct solutions.

就是让你输出N皇后问题的解法数目。

直接求解,每次还记录整个棋盘位置那种方法就不说了,必须超时。

有一个牛逼大了的超级无敌帅的位移动解法。我们暂且不表。看看我当时想的一个解法。

首先,对于皇后的那个递归方法,我有三个变量分别表示1.一个int值,表示递归到当前的level,当前的哪几个col被占领了,例如11011就表示我们下一个Q只能放在第三个(从第一个位置开始数)位置上了;2.一个hash table, 表示左对角线到目前为止,是否有Queen占领过了;2.一个hash table,表示右对角线是否有Queen占领过了。然后每次都去查询row上的可用格子,再去看看两个hash table上的可用格子,一起决定这一层我们选取那一(几)个作为备选项。

说说那个表示对角线的hash table,是一个Integer到boolean的映射。因为,所有某条固定左对角线上的点(row, col),row - col都是定值,那么可以用row - col表示一条左对角线嘛!同理可以用row + col表示右对角线嘛。

然后任意一个点,我们就知道它左右对角线的key了,就可以去那个hash 表里面查看是不是有Queen占领过啦。

所以,给出一个当前被占领的状态,一个左对角线被占领的状态,一个右对角线被占领的状态,我们就可以计算出下一步在哪里放Queen啦。方法如下:

  private static int available(int cur_row_status,
HashMap<Integer, Boolean> left_digra_status, HashMap<Integer, Boolean> right_digra_status, int row, int n){
int avail = cur_row_status;
for(int j = 0; j < n; j++){
if((left_digra_status.containsKey(row + j) && left_digra_status.get(row + j))
|| (right_digra_status.containsKey(row - j) && right_digra_status.get(row - j))) avail = set(avail, j);
}
return avail;
}

available方法

例如,返回如果是而110011(二进制),那么中间两位是可以放Q的。

那,我们就可以定义递归函数咯哦。

private static void collectSolutions(int cur_row_status,
HashMap<Integer, Boolean> left_digra_status, HashMap<Integer, Boolean> right_digra_status,
int row, int n, int[] count){
if(row == n) {
count[0]++;
return;
}
int avail = available(cur_row_status, left_digra_status,right_digra_status, row, n);
for(int i = 0; i < n; i++){
if(!isSet(avail, i)){
left_digra_status.put(row + i, true);
right_digra_status.put(row - i, true);
collectSolutions(set(cur_row_status, i), left_digra_status, right_digra_status, row + 1,
n, count);
left_digra_status.put(row + i, false);
right_digra_status.put(row - i, false);
}
}
}

collectSolutions

count里面就放我们的计数。注意每次递归子函数返回后,要重新设置对角线。col的那个状态不用重置了,因为java函数不会改变int值的。

主函数这样写:

 public static int  totalNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int cur_row_status = 0;
int[] count = new int[1];
HashMap<Integer, Boolean> left_digra_status = new HashMap<Integer, Boolean>();
HashMap<Integer, Boolean> right_digra_status = new HashMap<Integer, Boolean>();
collectSolutions(cur_row_status, left_digra_status, right_digra_status, 0, n, count);
return count[0];
}

然后我觉得我这方法已经不错了吧,结果还是让大集合潮湿了。

牛逼闪闪,刺瞎我的24k钛合金狗眼的位移算法来鸟。

 public int totalNQueens(int n){
cnt = 0;
upper = (1<<n)-1 ;
Queen(0,0,0);
return cnt;
} //为啥说大牛niub呢,看看我下面那个,再对比ld和rd,人大牛一眼就看出来了,没必要保存
//所有对角线信息啊。下一个状态,完全由当前状态决定!!
private void Queen(int row, int ld, int rd){//ld, left 对角线; rd, right 对角线
int pos, p;
if(row!=upper)
{
//so pos in binary is like, under current row/ld/rd restriction, what is available slot to put Q
pos = upper & (~(row | ld |rd));
while(pos!=0)//available is 1
{
p = pos & (-pos);//from right to left, the first "1" in pos
//now, we occupy the most right available position
pos = pos - p;//now take this available as ”Q“,pos kind of like a available slot marker
Queen(row+p,(ld+p)<<1,(rd+p)>>1);
}
}
else ++cnt;
}

Niubility N Queen

好一个不明觉厉,男默女泪的算法!

。。。。。

首先,再次承认和牛人的差距。

其次,反思,反思,深刻地反思。为毛牛人就知道这一点呢?其实所有中间信息都可以用一个整数来表示啊。

特别是那个左右对角线的事情,弄的本娃很郁闷。仔细想想,可不是嘛,当设置了一个Q以后,就是设置其左下方和右下方不能访问嘛。随着层次的深入(向最后一行靠近),对角线的状态可不就是左对角线左移,右对角线右移嘛。天,好有画面感的事情。

这里还有个小技巧。11100这个二进制数,怎么知道从右向左边第一个1的位置啊?

p = (pos) & (-pos)

我真是不知道这个,如果你也不知道负数在计算机中的表示方法的话,建议google之。

哦,这里有个关于这个算法的图图,看看有帮助。http://www.matrix67.com/blog/archives/266

我想去买这位blogger的书了。

总结:

1. 思考要有深度。就是说,理解一下,当前的信息到底是怎么样得出来的,而不是看表象。

2. 要有画面感

LeetCode 笔记系列 14 N-Queen II [思考的深度问题]的更多相关文章

  1. LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]

    题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...

  2. LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

    题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...

  3. LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...

  4. LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]

    题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ...

  5. LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...

  6. LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...

  7. LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]

    题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Fol ...

  8. LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]

    题目:Given n non-negative integers representing an elevation map where the width of each bar is 1, com ...

  9. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

随机推荐

  1. c3p0数据库连接池管理

    之前已经讲过dbcp可以用于数据库连接池进行管理.另一种技术c3p0也可以用于数据库连接池管理,其中Spring等框架都是基于c3p0技术进行数据库连接池管理的. 使用之前需要引入 c3p0-0.9. ...

  2. 解决Eclipse无法打开“Failed to load the JNI shared library”

    这是因为JDK配置错误所导致的现象. 一般说来,新购笔记本会预装64位的windows系统,而在网上下载软件时,32位会优先出现在页面中(现在来说是这个情况,但我认为未来64位会越来越普及). 如果你 ...

  3. Object-C中的数字对象

    #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { ...

  4. 8086汇编之 CALL 和 RET指令

    Ret 和 call 也是转移指令,可是他们跟jmp不同的是,这两个转移指令都跟栈有关系. <1> ret 用栈中的数据改动IP的地址,从而实现近转移 ( ip ) = ( (ss)*16 ...

  5. Python强制抛出自定义异常

    raise Exception("My Exception") 当程序运行到这行时,会抛出异常,打印出Exception: My Exception

  6. 基于注解的ssh框架之spring配置文件

    <?xml version="1.0" encoding="UTF-8"?> com.mysql.jdbc.Driver jdbc:mysql:// ...

  7. Win7-U盘安装出现"We were unable to copy your files. "

    使用Windows 7 USB/DVD Download Tool时,提示We were unable to copy your files. Please check your USB device ...

  8. jQuery插件开发全解析<转>

    jQuery插件的开发包括两种: 一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法.jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级 ...

  9. Scala中集合类型与java中集合类型转换

    对于java中的集合元素并不能在scala中拿来就用的,需要进行相应的转换. 1. 转换规则如下 从下面可以看出,有些可以相互转换的,有些只能单向转换: scala.collection.Iterab ...

  10. 禁止复制 + 锁右键 + 禁止全选(兼容IE Chrome等)

    function iEsc() { return false; }function iRec() { return true; }function DisableKeys() {    if (eve ...