0

I tried writing recursion to solve sudoku, and I'm having a problem with the recursion. If it's unsolvable its ok, but if it is solvable it is getting to infinite loop.

public static boolean recursion (int sodukuMatrix[][],int posRow, int posCol ,int i){

    if (posRow==0 && posCol==0 && i==10)
        return false;

    if(there is existing number){
        if (posCol==8 && posRow==8)
            return true;
        call recursion with next square
    }
    else {
        i=sodukuMatrix[posRow][posCol]+1;
        while (i<10){
            if (function: if I put i at the current location it is ok){
                sodukuMatrix[posRow][posCol]=i;        
                if (posCol==8 && posRow==8)
                    return true;
                call recursion with next square
            }
            else    
                i++;
        }
        sodukuMatrix[posRow][posCol]=0;
        return false;
    }
    return false;
}
}
3
  • 1
    Sounds like you have a version of this code that compiles. Having that would make this easier to figure out. Commented Mar 19, 2014 at 18:57
  • i am still newbie at programming so i dont really know how to do it (or what exactly you mean..) . thanks Commented Mar 19, 2014 at 19:04
  • The code you've posted does not get into an infinite loop, because it is not valid java. It doesn't compile, so you can't execute it at all. There's are syntax errors at: if(rec (cloneMatrix, sodukuMatrix, posRow, posCol+1 ,i)) }, and, obviously, at if (function: if I put i at the current location it is ok){. Commented Mar 19, 2014 at 19:15

1 Answer 1

1

To go a little down the rabbit hole. Solving Sudoko seems like an application of Constraint-Satisfaction in a context similar to the N-Queens Problem A MIN-CONFLICTS algorithm can be used in combination with Simulated Annealing to find the optimal solution.

Consider this pseudocode from Peter Norvig's Artificial Intelligence a Modern Approach

function MIN-CONFLICTS(csp, max_steps) returns a solution or failure
  inputs: csp, a constraint satisfaction problem
  max_steps, the number of steps allowed before giving up

  current <- an initial complete assignment for csp
  for I = 1 to max_steps do
    if current is a solution for csp then return current
    var <- a randomly chosen conflicted variable from csp.VARIABLES
    value <- the value v for var that minimizes CONFLICTS(var, v, current, csp)
    set var = value in current
  return failure

The CONFLICTS function counts the number of constraints violated by a particular value, given the rest of the current assignment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.