【发布时间】:2015-07-24 17:18:30
【问题描述】:
我正在尝试解决以下问题:“编写一个算法来打印在 8x8 棋盘上排列八个皇后的所有方式,以便它们都不共享同一行、列或对角线(即没有两个皇后分别攻击其他。)”
我很难理解为什么作者使用 Integer[] 而不是更常见的 int[],例如在作为 placeQueens 参数的“Integer[] columns”和“ArrayList results”中。我的假设是这是由于 Java 中的泛型,但我并不完全确定。
下面的代码sn-p。链接到页面底部的完整代码。
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
【问题讨论】:
-
这与泛型无关。即使值是 int,Java 也会在需要时将它们自动装箱为 Integer 类。 int 是原始类型,其中 Integer 是此原始类型 int 的包装类。尝试阅读 Java 和 Autoboxing/Unboxing 中的原始数据类型。
-
这里的用法完全是基于意见的。
-
除非我遗漏了一些明显的东西,否则这是一个直截了当的错误。你可以使用
int[]并且代码的行为是相同的(除了它会减少浪费)。 -
@NathanHughes 一般来说,是的。在这种特定情况下,这是无关紧要的。
-
在此示例中使用
Integer[]代替int[]没有任何优势,但有一些“一般”优势:例如默认值。尽管null毫无意义,但它仍然比0好。另一个优点是Integer[]是一个对象类型的数组,而int[]不能使用泛型确定为int的数组。这就是Arrays.asList(new int[]{1, 2, 3})无法按预期工作的原因。
标签: java recursion integer boxing