import java.util.*; public class SudokuSolver { public String solve(Board B){ Stack stackOfMoves = new Stack(); try{ int row = 0; int col = 0; int guess = 1; boolean badMove = true; while(badMove==true && row<9){ if(B.getFixedCell(row,col)==false) { //Check if the move is bad Move m = new Move(row,col,guess); badMove = B.isBad(m); if(badMove==false) { B.move(m); stackOfMoves.push(m); //Move to next cell if(col!=8) col++; else{ row++; col =0; } guess = 1; badMove=true; } else { //If there are more guesses, increment guess if(guess!=9) guess++; else { //go back and try the next guess for the top Move on stack Move m_last = stackOfMoves.pop(); row = m_last.getRow(); col = m_last.getCol(); Move tmp = new Move(row,col, 0); B.move(tmp); //If the top Move guess is '9', skip it while(m_last.getValue()==9) { m_last = stackOfMoves.pop(); row = m_last.getRow(); col = m_last.getCol(); Move tmp2 = new Move(row,col,0); B.move(tmp2); } //increment guess guess = m_last.getValue()+1; } } } else { //Move to next cell if(col!=8) col++; else{ row++; col =0; } } } }catch(EmptyStackException e){ return "This puzzle has no solution."; }; return B.toString(); } }