嗨,我刚刚参加了最后一年的编程考试,有人问我一个问题:使用什么排序和搜索算法来解决 8 个皇后问题。
如果我错了,请纠正我,但根本没有排序......我知道在放置女王和回溯期间需要基本级别的搜索,但是排序在哪里?如果有的话?
下面是我一直在看的,只是看不到它。
public class Queens
{
int[] positions;
int counter = 0;
boolean isFinished = false;
public Queens()
{
positions = new int[8];
placeQueens(0);
}
public boolean canPlaceQueen(int row, int column)
{
for (int i = 0; i < row; i++)
{
if (positions[i] == column || (i - row)== (positions[i]-column) || (i-row)== (column - positions[i]))
{
return false;
}
}
return true;
}
public void placeQueens(int row)
{
counter++;
printQueens();
for (int column = 0; column < 8; column++)
{
if (canPlaceQueen(row, column))
{
positions[row] = column;
if (row == 8-1)
{
System.out.println("FINAL " +counter);
isFinished = true;
printQueens();
}
else if(!isFinished)
{
placeQueens(row+1);
}
}
}
}
public void printQueens()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j< 8; j++)
{
if (positions[i] == j)
{
System.out.print("Q ");
}
else
{
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
}