我很难理解我在网上得到的代码。这是检查女王是否与其他女王发生冲突。有人能给我解释一下这是干什么的吗?第一个条件,我知道这是对同一行的检查,但是绝对值呢?
if ((board[i] == board[row]) || Math.abs(board[row] - board[i]) == (row - i))
{
return false;
}以下是完整的代码:
class NQueen {
private int[] board;
private int size;
private ArrayList allSolutions = null;
public int[] getBoard() {
return board;
}
public ArrayList getAllSolutions() {
return this.allSolutions;
}
public NQueen(int size) {
this.size = size;
board = new int[this.size];
this.allSolutions = new ArrayList();
}
public void place(int row) {
// base case
if (row == size) {
int[] temp = new int[size];
// copy in temp array
System.arraycopy(board, 0, temp, 0, size);
// add to the list of solution
allSolutions.add(new Solution(temp));
return ;
} else {
for (int i = 0; i < size; i++) {
board[row] = i;
/* when you place a new queen
* check if the row you add it in, isn't
* already in the array. since the value of arrray is
* the row, so we only need to check the diagonals no need to check for collisions on the left or right.
* As long as there is no duplicate values in the array.*/
if (valid(row)){
place(row + 1);
}
}
}
}
public boolean valid(int row) {
for (int i = 0; i < row; i++) {
// if same row or same diagonal
if ((board[i] == board[row]) || Math.abs(board[row] - board[i]) == (row - i))
{
return false;
}
}
return true;
}}
发布于 2020-03-01 08:33:45
如果你有一个二维的阵列和每个位置在板上的“单元格”在数组中,那么要在相同的对角线,一件必须有相同的水平和垂直距离。
Math.abs(board[row] - board[i]) == (row - i)仔细检查一下。Math.abs是因为第二部分可以是左上角、右上角、右下角和左下角.不确定您的算法是如何实现的,但是也可以使用第二个操作数的绝对值。
一个小板的例子:
1 2 3 4
1
2 x
3
4 y在这里,水平距离为2 (abs(1-3)),垂直距离为2 (abs(2-4))。
示例2:
1 2 3 4
1 x
2 y
3
4 这里的水平和垂直距离只有1 (abs(4-3)和abs(1-2))。
跟进
数组将女王在这一行中的位置存储在每个元素中。因此,它只是一个一维数组(不是我最初建议的二维数组)。
因此,对于我的第一个示例,您的数组将包含:
[ 0, 1, 0, 3 ](我认为来自OP的代码采用基于0的位置,但使用0 (new int[size])初始化数组元素。这可能是一个bug,因为0是一个有效的位置,并且可能与其他约束相冲突,也就是说,如果上一行或下一行的皇后未初始化(=位置0),您将无法在索引1上放置皇后。
回到示例(为了清晰起见,使用基于1的索引,以避免上面提到的错误):a[2] - a[4] == 1 - 3 (a[2] == 1,a[4] == 3)
如果将"y“块移到第2列,则将得到a[2] - a[4] != 1 - 3,因为它们不共享对角线(a[2] == 1,a[4] == 3)。
https://stackoverflow.com/questions/60473211
复制相似问题