I am having a problem about understanding the code i got online. It's the checking of the queen if there's a collision with other queens. Can somebody explain to me what does this do? The first condition, I knew it's the checking of the same row, but what about the absolute number?
if ((board[i] == board[row]) || Math.abs(board[row] - board[i]) == (row - i))
{
return false;
}
Here is the full code:
class NQueen {
private int[] board;
private int size;
private ArrayList allSolutions = null;
public int[] getBoard() {
return board;
}
public ArrayList getAllSolutions() {
return this.allSolutions;
}
public NQueen(int size) {
this.size = size;
board = new int[this.size];
this.allSolutions = new ArrayList();
}
public void place(int row) {
// base case
if (row == size) {
int[] temp = new int[size];
// copy in temp array
System.arraycopy(board, 0, temp, 0, size);
// add to the list of solution
allSolutions.add(new Solution(temp));
return ;
} else {
for (int i = 0; i < size; i++) {
board[row] = i;
/* when you place a new queen
* check if the row you add it in, isn't
* already in the array. since the value of arrray is
* the row, so we only need to check the diagonals no need to check for collisions on the left or right.
* As long as there is no duplicate values in the array.*/
if (valid(row)){
place(row + 1);
}
}
}
}
public boolean valid(int row) {
for (int i = 0; i < row; i++) {
// if same row or same diagonal
if ((board[i] == board[row]) || Math.abs(board[row] - board[i]) == (row - i))
{
return false;
}
}
return true;
}
}