现在我正在尝试解决这个问题,在一个8x8的电路板上有八个皇后,你必须把它们放在一个它们都不能捕获另一个的地方。这是一个非常流行的使用递归的问题,然而我仍然不能确切地知道为什么它不能工作。下面是用于检查放置是否有效的主要代码,如果是有效放置,则放置皇后,否则尝试将皇后放置在右侧一个单位的位置(新列,同一行)。代码如下:
private boolean placeQueen(int row, int column)
{
if(check(row, column))
{
board[column][row] = 'Q';
queenCount++;
return true;
}else if(column == board.length)
{
queenCount++;
return false;
}else
{
return (placeQueen(row, column + 1));
}
//return false;
}
private boolean check(int row, int column)
{
//checking vertical axis
for(int i = 0; i < board.length; i++)
{
if(board[column][i] == 'Q' && i != row)
{ //does not check its own row
return false;
}
}
int i = column;
int j = row;
//left one, up one
while(i >= 0 && j >= 0)
{
try{
if(board[i--][j--] == 'Q')
{
return false;
}else
{
i--;
j--;
}
}catch(ArrayIndexOutOfBoundsException e)
{
break;
}
}
i = column;
j = row;
//right one, up one
while(i <= 8 && j >= 0)
{
try{
if(board[i++][j--] == 'Q')
{
return false;
}else
{
i++;
j--;
}
}catch(ArrayIndexOutOfBoundsException e)
{
break;
}
}
return true;
}我只需要检查向上的对角线,因为我在它下降的时候放置了皇后。以下是输出,这是不正确的:
Q * * * * * * *
* Q * * * * * *
* * * Q * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * * Q *
* * * * Q * * *
* * * * * Q * *是我递归的方式,还是我检查对角线的方式?
下面是我运行它的方式
public void run()
{
createBoard();
while(queenCount != board.length)
{
placeQueen(queenCount, 0);
}
printBoard();
}发布于 2015-11-16 19:03:01
以下是上众多示例中的一个
希望这能帮上忙。
https://stackoverflow.com/questions/33723133
复制相似问题