题目: 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. MySQL replace into 用法

    讨人喜欢的 MySQL replace into 用法(insert into 的增强版) 在向表中插入数据的时候,经常遇到这样的情况:1. 首先判断数据是否存在: 2. 如果不存在,则插入:3.如果 ...

  2. 宏里面的(void)0

    在<c标准库>实现assert.h中有一个语句: #define assert(test) ((test)?(void)0 : _Assert(__FILE__":"_ ...

  3. ubuntu内部错误的解决办法

    在ubuntu使用过程中,出现下面错误: 对不起,Ubuntu 16.04出现了内部错误. 这并不是ubuntu16.04特有的问题,好像每一个ubuntu版本都有类似的问题. 解决的办法有2个. 1 ...

  4. Linux下解压tar.xz

    tar xvJf  ***.tar.xz 注意零散文件,最好放到文件夹里

  5. Linux(Ubuntu/Debian/CentOS/RedHat)下交叉编译boost库

    我用的软件版本如下(其他版本编译方法与此完全相同): Boost Ver: 1.55.0Compiler : GNU gcc 4.6 for ARM 1. 确保ARM编译成功安装,并配置好环境变量.2 ...

  6. java 清除 bom

    参考工具  http://akini.mbnet.fi/java/unicodereader/ Utf8BomRemover 清除bom的方法 package cn.com.do1.component ...

  7. 基础地图Android SDK

    开发者可利用SDK提供的接口,使用百度为您提供的基础地图数据.目前百度地图SDK所提供的地图等级为3-21级,所包含的信息有建筑物.道路.河流.学校.公园等内容. V3.7.0起,地图支持缩放至21级 ...

  8. saveFile()方法

    saveFile的原理就是将流写入到需要写入的文件,通过可以用“FileOutputStream”创建文件实例,之后过“OutputStreamWriter”流的形式进行存储,举例:public vo ...

  9. 2017年网站安全狗绕过WebShell上传拦截的新姿势

    本文来源:https://www.webshell.ren/post-308.html 今天有一位朋友发一个上传点给我 我一看是南方cms 有双文件上传漏洞 本来可以秒的 但是看到了 安全狗 从图片可 ...

  10. lua工具库penlight--01简介

    lua的设计目标是嵌入式语言,所以和其它动态语言(如python.ruby)相比其自带的库缺少很多实用功能. 好在有lua社区有Penlight,为lua提供了许多强大的功能,接下来的几篇博客,我会简 ...