I was having a look at the popular NQueen problem. The below code simply returns the number of possible ways. It gives different outputs depending upon the way in which the board matrix is passed.
// just a helper function
const isSafe = (board, row, col) => {
for (let i = row; i >= 0; i--) {
if (board[i][col]) return false;
}
for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j]) return false;
}
for (let i = row, j = col; i >= 0 && j < board.length; i--, j++) {
if (board[i][j]) return false;
}
for (let i = row; i >= 0; i--) {
if (board[i][col]) return false;
}
return true;
};
const getWays = (board, row) => {
if (row == board.length) {
return 1;
}
let count = 0;
for (let col = 0; col < board.length; col++) {
if (isSafe(board, row, col)) {
board[row][col] = true;
count += getWays(board, row + 1);
board[row][col] = false;
}
}
return count;
};
If i call getWays like below the output is 2 which is correct
const n = 4;
let board = new Array(n).fill(new Array(n).fill(false));
for (let i = 0; i < n; i++) {
board[i] = new Array(n).fill(false);
}
console.log(getWays(board, 0));
But if i call getWays like below the answer is 0 which is incorrect
const n = 4;
let board = new Array(n).fill(new Array(n).fill(false));
console.log(getWays(board, 0));
I don't understand how these 2 ways of creating the matrix are causing different outputs even though they generate same matrix. Can someone point out what am I missing with a little explaination and link to any documentation(if applicable/possible)
board, in the second snippetboardcontains the same array 10 times and if you change that array in one row all other rows change as well. And the same is true in java btw.