Hey everyone,
I’ve been working on the Sudoku Solver QA project, and I think I’ve got it very close to working correctly. The problem I’m having is that when I solve the puzzle, my function will reach the correct solution but then instead of returning that solution it will continue running and remove all of the correct numbers, reverting back to the original puzzle string.
I’m not sure why it’s doing this, because it looks like it should stop running the function and return the completed solution when it is reached.
Here is my solve function:
solve(puzzleString, row, col) {
let letter = {
'0': 'A',
'1': 'B',
'2': 'C',
'3': 'D',
'4': 'E',
'5': 'F',
'6': 'G',
'7': 'H',
'8': 'I'
}
if (!puzzleString) {
return { error: 'Required field missing' };
}
if (this.validate(puzzleString).error) {
return this.validate(puzzleString);
}
let solutionString = [...puzzleString];
if (col === 9) {
col = 0;
row++;
}
if (row === 9) {
console.log('if (row === 9) : ' + solutionString.join(''));
return { solution: solutionString.join('') };
};
let index = (row * 9) + col;
if (solutionString[index] != '.'){
return this.solve(solutionString.join(''), row, col + 1);
}
let coord = letter[row] + (col + 1);
for (let i = 1; i < 10; i++) {
if (!this.checkPlacement(solutionString.join(''), coord, i).conflict) {
solutionString[index] = i;
if (!this.solve(solutionString.join(''), row, col).error) {
console.log(solutionString.join(''));
return {solution: solutionString.join('')};
}else{
solutionString[index] = '.';
}
}
}
return { error: 'Puzzle cannot be solved'};
}
Is anyone able to give me any pointers on this?
Thank you!