Iām trying to solve the following problem: "Write an algorithm for printing all the ways of organizing eight queens on an 8x8 chessboard so that none of them share the same row, column or diagonal (i.e., others)"
I had trouble understanding why the author used Integer [] instead of the more common int [], for example, in the Integer [] and "ArrayList results" columns, which are parameters for placeQueens. My hypothesis is that this is due to generics in Java, but I'm not quite sure.
Below is a snippet of code. Link to the full code at the bottom of the page.
public static int GRID_SIZE = 8;
public static boolean checkValid(Integer[] columns, int row1, int column1) {
for (int row2 = 0; row2 < row1; row2++) {
int column2 = columns[row2];
if (column1 == column2) {
return false;
}
int columnDistance = Math.abs(column2 - column1);
int rowDistance = row1 - row2;
if (columnDistance == rowDistance) {
return false;
}
}
return true;
}
public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
if (row == GRID_SIZE) {
results.add(columns.clone());
} else {
for (int col = 0; col < GRID_SIZE; col++) {
if (checkValid(columns, row, col)) {
columns[row] = col;
placeQueens(row + 1, columns, results);
}
}
}
}
/: Cracking the Coding Interview. : https://github.com/gaylemcd/ctci/blob/master/java/Chapter%209/Question9_9/Question.java