运行之后程序可以随机给出八皇后的排布图。由于我水平有限。程序可能还有瑕疵,仅供大家交流讨论。八皇后问题的核心是,计算出中共有多少种排布方法。。我这程序写的还不完善,没有涉及到统计有多少种排布方法的部分。每次运行都可能是不一样的排布方式,如果大家有兴趣的话,可以在此基础上进行完善,统计下有多少种排布
代码如下:
/**八皇后问题
一个古老而著名的问题,是回溯算法的典型案例。
在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,
即任意两个皇后都不能处于同一行、同一列或同一斜线上。
*/
class EightQueens
{ static String[][] map = {
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "},
{"| ","| ","| ","| ","| ","| ","| ","| ","| "}
};
static int [] row = new int[8]; //行
static int [] col = {-1,-1,-1,-1,-1,-1,-1,-1}; //列 将初始的列数组置成-1,避免和第0列的坐标混淆
static int count; // 计数器
public static void main(String[] args)
{
while(!findEightQueens());
for(int i = 0; i < 8;i++){
System.out.println("皇后"+(i+1)+" "+"行:"+row[i]+" 列:"+col[i]);
}
for(int i = 0; i < 8; i++){
map[row[i]][col[i]] = "|*";
}
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
System.out.print(map[i][j]);
}
System.out.println();
}
}
public static boolean findEightQueens(){
boolean isError = false;
int temp=0; // 随机数暂存变量
for(int i = 0;i < 8;i++){
row[i] = i; //每一个皇后的行坐标是确定的,第一个皇后的行坐标就为0,第二个为2,以此类推
while(true){
if(i == 0){
col[i] = (int) (Math.random() * row.length); //产生的第一个皇后的列位置。 至此第一个皇后具体的位置就已经确定。
break;
}
boolean col_Ok = true;
temp = (int) (Math.random() * row.length); // 随机产生皇后列的位置坐标
for(int j = 0; j < i; j++){
count++;
if(count == 30){ // 尝试随机产生30次下一个皇后的列的位置。如果运行30次还不能找到正确的位置 说明前面皇后的位置排的有问题,程序不能给出正确的结果
col_Ok = false;
isError = true; // 把错误标志位置成true
count=0;
break;
}
//自己参透的算法核心 temp == col[j] 判断两个皇后不同列 temp == (col[j]-(i-j)) || temp == (col[j]+(i-j)) 判断任意两个皇后位置不在同一对角线上
if(temp == col[j] || temp == (col[j]-(i-j)) || temp == (col[j]+(i-j))){
col_Ok = false;
break;
}
col_Ok = true;
}
if(col_Ok){ // 2,3,4...8 号皇后的列坐标正确标志位
col[i] = temp; // 2,3,4...8 号皇后确定列坐标。 至此皇后的行列坐标都有了,皇后的位置确定了。
break;
}
if(isError){ //前几个皇后随机产生的位置有问题。程序出错。
return false;
}
}
}
return true;
}
}
|
|