您的位置:首页 > 其它

第一次实验,八皇后问题

2014-06-12 09:56 267 查看
public class EightQueen {
private int index = 1;
private final static int SCALE = 8;
private int[] answer = new int[SCALE];

private void initArray() {
for (int i = 0; i < answer.length; i++) {
answer[i] = -1;
}
}

private boolean canStay(int row, int col) {
for (int i = 0; i < row; i++)
{
if (answer[i] == col  || Math.abs(row - i) == Math.abs(col - answer[i]))
{
return false;
}
}
return true;
}

private void calculate() {
for (int row = 0; row < SCALE; row++)
{
if (answer[row] == -1)
{
answer[row] = 0;
}

for (int col = answer[row]; col <= SCALE; col++)
{
if (col == SCALE)
{
answer[row] = -1;
row--;
if (row < 0)
{
return;
}
col = answer[row];
continue;
}

if (canStay(row, col))
{
answer[row] = col;
if (row == SCALE - 1)
{
showmsg();
continue;
}
break;
}
}
}
}

private void showmsg() {
if (index<4)
{
System.out.println(" - 第" + index + "种方案 -");
for (int i = 0; i < answer.length; i++)
{
for (int j = 0; j < SCALE; j++)
{
if (answer[i] == j)
{
System.out.print("Q ");
} else {
System.out.print("X ");
}
}
System.out.println("");
}
System.out.println("\n");
index++;
}
}

public EightQueen() {
initArray();
calculate();
}

public static void main(String[] args) {
System.out.println("列举"+SCALE+"皇后问题的前 3 种方案!");
System.out.println();
EightQueen eightQueen = new EightQueen();
}
}


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: