这段时间一直在研究oracle 性能的优化加python的学习,所以没什么具体产量,正好看到python里有个例题是解决经典算法八皇后的,就手痒想这怎么用java去实现,当然最开始第一反映是两层for去死循环,对于一个有点想法或者编程经验的程序猿来说,这是绝对不应该的。
可能各位同学有的没听过八皇后算法
这里解释一下
八皇后问题是一个以国际象棋为背景的问题:如何能够在8×8的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。
刚开始看的时候只考虑了邻近两行的可能,即上行和下行,没有考虑到隔着的行数,所以代码也就有可以完善的部分。。
代码分为两个部分
第一个部分 是循环+递归(对行数进行递归,对列数进行循环)
第二个部分 检查当前位置是否可以摆放皇后
贴上代码
package lobs.jibunn.mb.jp.suanfa;
public class EightQueen {
static int num = 0;
public EightQueen() {
// TODO Auto-generated constructor stub
for(int i = 0; i < 8;i++) {
for(int j = 0; j < 8;j++) {
a[i][j] = 0;
}
}
}
static int a[][] = new int[8][8];
public static void main(String args[]) {
placeQueen(0);
}
public static void placeQueen(int x){
for(int i= 0;i < 8; i++) {
if (x == 8 ) {
printResult();
break;
}
if(checkPosition(x,i)) {
a[x][i] = 1;
placeQueen(x+1);
}
}
}
public static boolean checkPosition(int x, int y) {
for (int i = 0;i < 8; i++) {
a[x][i] = 0;
}
if (x == 0) {
return true;
}
if ( y == 0
&& x < 7) {
if (a[x-1][y] +
+ a[x-1][y+1] > 0
) {
return false;
} else {
return true;
}
}
if ( x == 7
&& y == 0) {
if (a[x-1][y] +
+ a[x-1][y+1] > 0
) {
return false;
} else {
return true;
}
}
if ( x == 7
&& y < 7) {
if (a[x-1][y] +
+ a[x-1][y+1]
+ a[x-1][y-1]> 0)
{
return false;
} else {
return true;
}
}
if ( y == 7
&& x <= 7) {
if (a[x-1][y]
+ a[x-1][y-1] > 0
) {
return false;
} else {
return true;
}
}
if (x == 7 && y == 0) {
if (a[x-1][y] + a[x-1][y+1] == 0) {
return false;
}else {
return true;
}
}
if (a[x-1][y +1]
+ a[x-1][y-1]
+ a[x-1][y] > 0
) {
return false;
}
return true;
}
private static void printResult(){
System.out.print(num++ +"-------------------------------------");
for(int i = 0; i < 8;i++) {
System.out.print("\n");
for(int j = 0; j < 8;j++) {
System.out.print(a[i][j]);
}
}
System.out.print("\n");
}
}
但是注意了
这个检验只对前后左右斜8个位置进行判断,并不包括隔行,有兴趣的同学可以自己完善下啦
本文介绍了一种使用Java实现八皇后问题的解决方案。通过循环加递归的方式对行数进行递归,对列数进行循环,同时提供了一个检查当前位置是否可以摆放皇后的辅助函数。
1万+

被折叠的 条评论
为什么被折叠?



