我正在尝试解决以下问题:“编写一个算法来打印在一个 8x8 的棋盘上排列八个皇后的所有方式,以便它们中没有一个共享相同的行、列或对角线(即没有两个皇后互相攻击其他。)”
我无法理解为什么作者使用 Integer[] 而不是更常见的 int[],例如在作为 placeQueens 参数的“Integer[] 列”和“ArrayList 结果”中。我的假设是这是由于 Java 中的泛型,但我不完全确定。
下面的代码片段。链接到页面底部的完整代码。
public static int GRID_SIZE = 8;
/* Check if (row1, column1) is a valid spot for a queen by checking if there
* is a queen in the same column or diagonal. We don't need to check it for queens
* in the same row because the calling placeQueen only attempts to place one queen at
* a time. We know this row is empty.
*/
public static boolean checkValid(Integer[] columns, int row1, int column1) {
for (int row2 = 0; row2 < row1; row2++) {
int column2 = columns[row2];
/* Check if (row2, column2) invalidates (row1, column1) as a queen spot. */
/* Check if rows have a queen in the same column */
if (column1 == column2) {
return false;
}
/* Check diagonals: if the distance between the columns equals the distance
* between the rows, then they're in the same diagonal.
*/
int columnDistance = Math.abs(column2 - column1);
int rowDistance = row1 - row2; // row1 > row2, so no need to use absolute value
if (columnDistance == rowDistance) {
return false;
}
}
return true;
}
public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
if (row == GRID_SIZE) { // Found valid placement
results.add(columns.clone());
} else {
for (int col = 0; col < GRID_SIZE; col++) {
if (checkValid(columns, row, col)) {
columns[row] = col; // Place queen
placeQueens(row + 1, columns, results);
}
}
}
}
问题/代码来源:Cracking the Coding Interview。完整代码链接:https://github.com/gaylemcd/ctci/blob/master/java/Chapter%209/Question9_9/Question.java
最佳答案
在Java中,Integer
代表一个对象,而int
是一个原始类型。 Integer
类支持更多功能,并且可以保存 null
值。另外,ArrayList
只能包含Integer
等对象。
ArrayList<int[]> results = new ArrayList<int[]>();
在上面修改后的代码中,int[]
仍然有效,因为它被认为是一个对象。但是,作者可能正在寻求一致性或需要 Integer
对象的额外功能。这是作者的喜好或无知的问题。
关于java - 使用 Integer[] 与 int[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616275/