最近从零开始学习JAVA,特地开了一个号来记录一下我的学习过程,希望自己能够坚持下去。
八皇后问题是回溯算法的经典案例:在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
思路其实挺简单易懂的:
从第一行第一列开始,放置第一个皇后,然后接着放置第二行、第三行直至第八行的皇后,当第八行的皇后放置完之后便得到了一个解。这里的放置过程是需要进行判断的,即要满足任意两个皇后不能处于同一列或者同一斜线上。至于为什么不对“处于同一行”这个情况进行判断,是因为按照我们的思路,应该是从第一行顺序放置到第八行,所以不存在两个皇后处于同一行的情况。
如果我们能够求得第一个皇后在第一行第一列的所有解,接下来我们只要让第一个皇后置于第二列...第八列,就能得到八皇后问题的所有解。
那么问题就是,我们如何求得第一个皇后在第一行第一列的所有解呢?
化繁为简,我们先找到第一个解:按照我们的思路,第一次放置应该是(用数组下标表示):(0,0)->(1,2)->(2,4)->(3,1)->(4,3)->?这时候我们发现,在我们放置第六行的皇后时,无论放置在哪一列都不能满足题目的要求,此时就应该回溯到(4,3)这个坐标,继续寻找其他满足放置条件的列。假设找到第八列