八皇后问题解:循环和递归方法(想了1.5天我是不是太菜!)
循环方法代码:
/**
* 参考:http://wenku.baidu.com/view/e67023c12cc58bd63186bd18.html
*
*
*/
public class QueeTestXunHuan
{
private void quee()
{
int num = 0;
int[] a = new int[9];
for (a[1] = 1; a[1] <= 8; a[1]++)
{
for (a[2] = 1; a[2] <= 8; a[2]++)
{
if (0 == chect(a, 2))
{
continue;
}
for (a[3] = 1; a[3] <= 8; a[3]++)
{
if (0 == chect(a, 3))
{
continue;
}
for (a[4] = 1; a[4] <= 8; a[4]++)
{
if (0 == chect(a, 4))
{
continue;
}
for (a[5] = 1; a[5] <= 8; a[5]++)
{
if (0 == chect(a, 5))
{
continue;
}
for (a[6] = 1; a[6] <= 8; a[6]++)
{
if (0 == chect(a, 6))
{
continue;
}
for (a[7] = 1; a[7] <= 8; a[7]++)
{
if (0 == chect(a, 7))
{
continue;
}
for (a[8] = 1; a[8] <= 8; a[8]++)
{
if (0 == chect(a, 8))
{
continue;
}
else
{
for (int i = 1; i <= 8; i++)
{
System.out.println(a[i]);
}
putout(a); // 打印图案
num++;
}
System.out.println("*****:" + num);
}
}
}
}
}
}
}
}
System.out.println(num);
}
/**
* 约束条件 1 : 不在同一列 X[i] != X[j] 2 : 不在同一主对角线上 X[i]- i != X[j] - j 3:不在同一副对角线上
* X[i] + i != X[j] + j
*
* 2,3整合 Math.abs(Xi - Xj) != Math.abs(i - j) Math.abs() 表示求绝对值
*
*
* @param a
*
* @param n
* @return
*/
private int chect(int[] a, int n) // 检查条件不能放皇后的返回0
{
int nn = a[n];
// TODO Auto-generated method stub
for (int i = 1; i <= n - 1; i++)
{
int ii = a[i];
if (a[i] == a[n] || (Math.abs(ii - nn) == Math.abs((i - n))))
{
return 0;
}
}
return 1;
}
private void putout(int[] a) // 打印图案 数组a1--a8表示行 里面的值表示列
{
for (int i = 1; i <= 8; i++)
{
for (int j = 1; j <= 8; j++)
{
if (a[i] == j)
{
System.out.print("@");
}
else
{
System.out.print("-");
}
}
System.out.println();
}
}
public static void main(String[] args)
{
QueeTestXunHuan qtxh = new QueeTestXunHuan();
qtxh.quee();
}
}
递归方法代码如下:
/**参考:
* http://wenku.baidu.com/view/e67023c12cc58bd63186bd18.html
*
*
*/
public class QueeTestDiGui
{
int[] a = new int[9];
int num = 0;
private void go(int k)
{
if (k > 8)
{
return;
}
else
{
for (int i = 1; i <= 8; i++) // i表示每一行的列
{
a[k] = i; // a[k]表示行
if (chect(a, k) == 0) // 不能放皇后的返回
{
continue;
}
if (chect(a, k) == 1) // 能放的检查是否能放
{
if (k == 8) // 检查是否已经到第8行是则输出
{
for (int j = 1; j <= 8; j++)
{
System.out.println(a[j]);
}
num++;
putout(a);
System.out.println("****:" + num);
}
go(k + 1); // 没到第8继续往下放
}
}
}
}
/**
* 约束条件 1 : 不在同一列 X[i] != X[j]
* 2 : 不在同一主对角线上 X[i]- i != X[j] - j
* 3:不在同一副对角线上 X[i] + i != X[j] + j
*
* 2,3整合 Math.abs(Xi - Xj) != Math.abs(i - j) Math.abs() 表示求绝对值
*
*
* @param a
* @param n
* @return
*/
private int chect(int[] a, int n)
{
int nn = a[n];
for (int i = 1; i <= n - 1; i++)
{
int ii = a[i];
if (a[i] == a[n] || (Math.abs(ii - nn) == Math.abs((i - n))))
{
return 0;
}
}
return 1;
}
private void putout(int[] a) // 打印图案 数组a1--a8表示行 里面的值表示列
{
for (int i = 1; i <= 8; i++)
{
for (int j = 1; j <= 8; j++)
{
if (a[i] == j)
{
System.out.print("@");
}
else
{
System.out.print("-");
}
}
System.out.println();
}
}
public static void main(String[] args)
{
QueeTestDiGui qtdg = new QueeTestDiGui();
qtdg.go(1);
}
}