每天刷个算法题20160519:回溯法解八皇后
Posted 小飞_Xiaofei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每天刷个算法题20160519:回溯法解八皇后相关的知识,希望对你有一定的参考价值。
版权所有。所有权利保留。
欢迎转载,转载时请注明出处:
http://blog.csdn.net/xiaofei_it/article/details/51502622
为了防止思维僵化,每天刷个算法题。已经刷了几天了,现在发点代码。
我已经建了一个开源项目,每天的题目都在里面:
https://github.com/Xiaofei-it/Algorithms
绝大部分算法都是我自己写的,没有参考网上通用代码。读者可能会觉得有的代码晦涩难懂,因为那是我自己的理解。
最近几天都是在写一些原来的东西,大多数是非递归。以后准备刷点DP、贪心之类的题。
下面是回溯法八皇后:
/**
*
* Copyright 2016 Xiaofei
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package xiaofei.algorithm;
/**
* Created by Xiaofei on 16/5/19.
*/
public class EightQueensPuzzle
/**
* 八皇后(回溯法)
* pos[n]
* 竖排:值相同
* 左上到右下:i - j = pos[i] - pos[j] --> i - pos[i] = j - pos[j]
* 左下到右上:i - j = pos[j] - pos[i] --> i + pos[i] = j + pos[j]
*
* 每次都要O(n^2)判断有点蛋疼,不知道有没有优化方案。
* 现在自己优化一下:
* hash判断
* 竖排:hash[SIZE]
* 左上到右下:i - pos[i] = j - pos[j] 从-(SIZE-1)到(SIZE-1) 为了从0开始,偏移(SIZE-1)
* 左下到右上:i + pos[i] = j + pos[j] 从0到2*(SIZE-1)
*/
private static final int SIZE = 8;
private static int number = 0;
private static void print(int[] pos)
System.out.println(++number);
int length = pos.length;
for (int i = 0; i < length; ++i)
System.out.print(" " + pos[i]);
System.out.println();
for (int i = 0; i < length; ++i)
for (int j = 0; j < pos[i]; ++j)
System.out.print('+');
System.out.print('*');
for (int j = pos[i] + 1; j < SIZE; ++j)
System.out.print('+');
System.out.println();
public static void calculate()
int[] pos = new int[SIZE];
boolean[] hash1 = new boolean[SIZE];
boolean[] hash2 = new boolean[SIZE * 2 + 1];
boolean[] hash3 = new boolean[SIZE * 2 + 1];
int last = 0;
pos[last] = -1;
while (last >= 0)
if (last == SIZE)
print(pos);
--last;
else
boolean flag = false;
if (pos[last] >= 0)
hash1[pos[last]] = false;
hash2[last - pos[last] + SIZE - 1] = false;
hash3[last + pos[last]] = false;
while (pos[last] < SIZE - 1)
++pos[last];
if (!hash1[pos[last]] && !hash2[last - pos[last] + SIZE - 1] && !hash3[last + pos[last]])
hash1[pos[last]] = true;
hash2[last - pos[last] + SIZE - 1] = true;
hash3[last + pos[last]] = true;
++last;
if (last < SIZE)
pos[last] = -1;
flag = true;
break;
if (!flag)
--last;
以上是关于每天刷个算法题20160519:回溯法解八皇后的主要内容,如果未能解决你的问题,请参考以下文章