Hi all, I am a bit stuck on the Sudoku solver recursion part. Recursion has always been a pain for me. I sort of get it, but not quite. Watched this video Python Sudoku Solver - Computerphile - YouTube, and I think I understand the concept, but when I try to do it, it does not work. So obviously I don’t.
In theory, I loop over all rows/cols. When I find an empty field I check if any value from 1-9 is allowed in that field, by running the 3 helpers. If it is allowed, I set that specific row/col value of the puzzle string to the current value.
Then I should run the solve() on the updated string. If I run into a dead-end I should return, reset the row/col back to “.” and continue?
What am I doing wrong here?
Your code so far
Here is my code:
https://repl.it/@Aigarsss/boilerplate-project-sudoku-solver
solve(puzzleString) {
let puzzleArray = puzzleString.split("");
for (let i = 0; i < 9; i++){
let row = i + 1;
for (let x = 0; x < 9; x++){
let currentPos = i * 9 + x
let col = x + 1;
if (puzzleArray[currentPos] == "."){
// loop through numbers 1-9
for (let y = 1; y <= 9; y++){
//do all 3 checks on each number. checkRowPlacement, checkColPlacement, checkRegionPlacement
let checkRow = this.checkRowPlacement(puzzleString, row, col, y);
let checkCol = this.checkColPlacement(puzzleString, row, col, y);
let checkRegion = this.checkRegionPlacement(puzzleString, row, col, y);
if (checkRow && checkCol && checkRegion) {
console.log(`got here on row ${row}, col ${col}, num ${y}`)
puzzleArray[currentPos] = y.toString();
this.solve(puzzleArray.join(""))
puzzleArray[currentPos] = "."
}
// console.log(`Check for row ${row}, col ${col}, num ${y}:
// checkRow = ${checkRow}
// checkCol = ${checkCol}
// checkRegion = ${checkRegion}`)
}
return
}
}
}
return puzzleArray.join("");
}
Challenge: Sudoku Solver
Link to the challenge: