Need help with reverse tracking algorithm to create sudoku board

I wrote an algorithm to create a Sudoku board, but it does not work. I wrote this based on this , although it differs in that I wrote a lot of my code before I came across this.

Code

I have a multidimensional array configured to store values ​​called matrix . matrix consists of 9 arrays, which are rows, and each of them contains 9 columns. Therefore, to get the value in the column of row 4, I would use

 matrix[3][6]; 

Function to solve all squares:

 var populateMatrix = function() { var possibles = generatePossibleNumbersArray(); var found = false; for(var i=0; i< matrix.length; i++) { for(var j=0; j< matrix[i].length; j++) { while(possibles[i][j].length > 0) { var rnd = Math.floor(Math.random() * possibles[i][j].length); var num = possibles[i][j].splice(rnd, 1)[0]; if(isValid(i, j, num)) { matrix[i][j] = num; found = true; break; } else { found = false; continue; } } if(!found) { possibles[i][j] = [1,2,3,4,5,6,7,8,9]; j -= 2; } } } } 

generatePossibleNumbersArray() is just a helper function to create a multidimensional array just like matrix , except that it is initialized to store an array of integers 1-9 for each cell. During the populateMatrix() function, these possible numbers are reset to zero for each cell.

Problem

Cannot complete the matrix every time because j ends with -1 . This is due to the fact that as more and more cells are solved, it becomes more difficult for the algorithm to find the value for the cell so that it recedes. But eventually it ends back until j == -1 .

I really thought this algorithm would work, and I spent all day trying to plunge into it, but I'm at a dead end, so any light that can shed on it will be greatly appreciated.

I thought, β€œI know, I will write a javascript function to solve Sudoku. How hard can it be? '. How wrong I was.


[DECISION]

Based on a comment from @ Steve314 (which he now deleted!), I added matrix[i][j] = undefined to if(!found) { ... , and now the algorithm works and quickly clears up.

If anyone is interested, here is the complete code .

+4
source share
1 answer

Backtracking algorithms usually restore state if the branch fails and makes the next possible move. Therefore, if accidentally filling in a field creates an unsuccessful branch, simply write back what was originally there.

+3
source

All Articles