My implementation of recursion involves trying different pieces in a matrix:
function solve(matrix, pieces) {
// Get next -1
let nextEmpty = getNextEmtpy(matrix);
if (!nextEmpty) {
console.log(matrix)
solutions.push(matrix);
}
let row = nextEmpty.row;
let col = nextEmpty.col;
// Try all pieces that are not in the matrix
for (let i = 1; i < pieces.length; i++) {
if (matrix.flat().includes(i)) continue;
for (let r = 0; r < 4; r++) {
let fit = rotatePiece(pieces[i]);
if (col == 0) {
if (fit[0] != 0) continue;
}
if (row == 0) {
if (fit[1] != 0) continue;
}
if (col == matrix[0].length - 1) {
if (fit[2] != 0) continue;
}
if (row == matrix.length - 1) {
if (fit[3] != 0) continue;
}
// If the piece is not in a border
if (col > 0) {
if (fit[0] != pieces[matrix[row][col - 1]][2]) continue;
}
if (row > 0) {
if (fit[1] != pieces[matrix[row - 1][col]][3]) continue;
}
// Add the piece to the matrix
matrix[row][col] = i;
// Update pieces
pieces[i] = fit;
// Recurse
let solution = solve(matrix, pieces);
// Reset the value
matrix[row][col] = -1;
}
}
return false;
}
The expected output and variable values seem correct except when adding the matrix to solutions array which starts as an empty array []:
[
[ 25, 1, 17, 24, 7 ],
[ 19, 16, 23, 8, 15 ],
[ 12, 14, 4, 2, 21 ],
[ 5, 9, 11, 6, 18 ],
[ 10, 13, 22, 20, 3 ]
]
However, instead of this result, it adds the starting value of matrix:
[
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ]
]
This behavior seems unexpected. Why could this be happening?