java - 使用 Integer[] 与 int[]

标签 java recursion integer boxing

我正在尝试解决以下问题:“编写一个算法来打印在一个 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/

相关文章:

C Scanf 突然停止读取值

java - 将对象解析为整数

java - Selenium Jenkins Linux TestNG - 如何运行?

java - 在 Java 中向零舍入

java - 在 JDBC 连接上设置时区

algorithm - 回文递归算法的时间复杂度

java - 使用 Java Files.copy 复制后出现空白页的 PDF 文件

javascript - 递归搜索 JSON 字符串字典,查找键值对在 "name"中的所有值

java - 在 merge 方法中返回多个变量

c - 当用户可以在 c 中提供任意多的输入时,如何确定最小和最大的正整数输入?