1

I´m trying to do a Sudoku program in Javascript but I have a little problem with Backtracking algorithm, I have the "same" code in Java and works perfectly, the problem is (after debugging it) "k" is the value that is going to be the new value of matriz, and..... when a cell cannot be set by k return to the stack (RECURSIVITY) but when I apply Backtracking algorithm k is not set by the last value of k. I run my application in Safari, Chrome, and Firefox and give me the same result (100% sure is my code)

var matriz = [
    [9, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0]
];
function resolver(matriz)
{
    for (i = 0; i <= 8; i++)
    {
        for (j = 0; j <= 8; j++)
        {
            if (matriz[i][j] != 0)
            {
                continue;
            }
            for (k = 1; k <= 9; k++)
            {
                if (insertar(matriz, i, j, k) == true)
                {
                    matriz[i][j] = k;
                    b = resolver(matriz);
                    if (b == true)
                    {
                        return true;
                    }
                    matriz[i][j] = 0;
                }
            }
            return false;
        }
    }
    alert("SOLUCIÓN");
    return true;
    //SET CADA ELEMENTO DE LA MATRIZ;
}
function insertar(matriz, i, j, k)
{
    for (a = 0; a <= 8; a++)
    {
        if (a != i && matriz[a][j] == k)
        {
            return false;
        }
    }
    for (a = 0; a <= 8; a++)
    {
        if (a != j && matriz[i][a] == k)
        {
            return false;
        }
    }
    y = Math.floor((i / 3)) * 3;
    x = Math.floor((j / 3)) * 3;
    for (a = 0; a < 3; a++)
    {
        for (b = 0; b < 3; b++)
        {
            if (a != i && b != j && matriz[y + a][x + b] == k)
            {
                return false;
            }
        }
    }
    return true; 
}
Ivan Garcia
  • 111
  • 1
  • 6
  • To make it easier for someone to digest your code, you should clean up the extraneous whitespace. – Mark Feb 23 '15 at 05:50
  • Sorry ... Editing... – Ivan Garcia Feb 23 '15 at 05:59
  • 1
    Your loop variables should be local and declared explicitly with `var`. You use [implicit globals](http://stackoverflow.com/questions/15985875/effect-of-declared-and-undeclared-variables), which will be shared among all recursive calls. Change your loops `for (x = 0; ...)` to `for (var x = 0; ...)` and it should work. – M Oehm Feb 23 '15 at 11:35
  • Thank you very much... that was my problem – Ivan Garcia Feb 23 '15 at 13:32

0 Answers0