user4740600
user4740600

Reputation: 89

Sudoku Backtracking

Below is my solve method. When I call it in my main method, nothing happens and all the succeeding it is not executed but no error is reported by eclipse.

    public boolean solve(int r, int c){
    if(c>8){
        c=0;
        r++;
    }
    if(r>8){
        return true;
    }
    while(table[r][c].value!=0){
        c++;
        if(c>8){
            c=-0;
            r++;
        }
        if(r>8){
            return true;
        }
    }
    for(int k=1;k<10;k++){
        if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){
            table[r][c].value=k;
            solve(r,c);
        }
    }
    table[r][c].value=0;
    return false;
}

Will this algorithm backtrack? If not, why?

Upvotes: 1

Views: 71

Answers (1)

smadhava
smadhava

Reputation: 63

It looks like a logical error and hence eclipse does not report anything.

In for loop section of your code, you should have something like this

 for(int k=1;k<10;k++){
        if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){
            table[r][c].value=k;
            if(solve(r,c)){
                return true;
             }
             table[r][c].value=0;
        }
    }

In your case you are un-assigning the table outside the for loop, which prevents the code from backtracking.

Here is my code for solving sudoku. Hope it helps.

Upvotes: 1

Related Questions