Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I can see one problem in your code. You have a loop that is sawing off the branch it sits on:</p> <pre><code>for(int c = 0; c &lt; mySudoku[celli][cellj].getPossibleValues().size() - 1; c++) { ... mySudoku[celli][cellj].setValue(mySudoku[celli]cellj].getPossibleValues().get(c)); ... } </code></pre> <p>Apart from that, you are missing one of the values, it should be <code>for(c=0; c!=size; ++c)</code>, i.e. not <code>size - 1</code>. Also, calling getPossibleValues() just once would make this code much more readable. Lastly, catching and ignoring a stack underflow is just stupid, because it hides errors in your algorithm, as far as I can tell. If you don't know how to handle an error, don't just silence it. Since java requires you to catch it, put it in the outermost place possible or at least abort or do <em>something</em>, but don't ignore it!</p> <p>One more thing: You are recursing and passing the context data via <code>mySodoku</code> and <code>myStack</code>. This is completely missing the point of recursion (or at least the way it's typically used), because the function call stack is the only stack you need. Using these to pass parameters only makes things more complicated than necessary. Instead, the function should return a partial sodoku puzzle and return either the fully solved puzzle or null. Using is easier to distinguish than the exception you're using now, and it's a regular and expected thing, not really exceptional. Then, when trying different choices, you set the cell to the values in turn and recurse, until the call doesn't return null. If none of the choices returns a solution, you clear the cell and return null yourself.</p> <pre><code>solve(sodoku): if sodoku is solved: return true if sodoku is invalid: return false c = some empty cell for v in 1...9: // set to a value and recurse c = v if solve(sodoku): // found a solution return true // no solution found, clear cell and return failure c = null return false </code></pre> <p>BTW: This strategy is called "backtracking". Using a cell with the least amount of possible values is called "pruning", which allows you to cut off whole branches from the search tree. Actually determining the possible values also helps avoiding a few futile attempts.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload