我试图解决以下问题:“编写一个算法来打印在8×8国际象棋棋盘上安排八个皇后的所有方法,这样它们就不会共享相同的行,列或对角线(即没有两个皇后互相攻击.) “
我无法理解为什么作者使用Integer []而不是更常见的int [],例如在“Integer [] columns”和“ArrayList results”中,它们是placeQueens的参数.我的假设是这是由于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);
}
}
}
}
问题/代码的来源:破解编码面试.链接到完整代码:https://github.com/gaylemcd/ctci/blob/master/java/Chapter%209/Question9_9/Question.java
最佳答案 在Java中,Integer表示对象,而int是基本类型. Integer类支持更多函数,并且可以保存空值.另外,ArrayList只能包含Integer等对象.
ArrayList<int[]> results = new ArrayList<int[]>();
在上面的修订代码中,int []仍然可以工作,因为它被认为是一个对象.但是,作者可能正在寻求一致性或者需要Integer对象的额外功能.这是作者的偏好或无知的问题.