Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sudoku solver using backtracking

I've recently been working on a backtracking sudoku solving algorithm and currently I'd like to ask on how I should go about to change my solve() method from void to a boolean.

I'm using a very simple backtracking algorithm, and it's currently working fine, but I'd rather have a boolean instead of a void, because having a printstack isn't very nice...

Thanks!

public class Backtracking{


 static int backtrack = 0;


 //check if valid in row
protected static boolean validInRow(int row, int value)
{
   for( int col = 0; col < 9; col++ )
     if( board[row][col] == value )
         return false ;

  return true ;
}

  //check if valid in column
protected static boolean validInCol(int col, int value)
{
    for( int row = 0; row < 9; row++ )
     if( board[row][col] == value )
        return false ;

  return true ;
 }

 //check if valid in 3*3
protected static boolean validInBlock(int row, int col, int value)
{
  row = (row / 3) * 3 ;
    col = (col / 3) * 3 ;

   for( int r = 0; r < 3; r++ )
      for( int c = 0; c < 3; c++ )
       if( board[row+r][col+c] == value )
         return false ;

   return true ;
 }




      //call other methods
public void solve(int row, int col) throws Exception
{

   if(row > 8)
     throw new Exception("Solution found") ;
  else
  {

     while(board[row][col] != 0)
     {
        if( ++col > 8 )
        {
           col = 0 ;
           row++ ;


           if( row > 8 )
              throw new Exception( "Solution found" ) ;
        }
     }


     for(int value = 1; value < 10; value++)
     {
        if(validInRow(row,value) && validInCol(col,value) && validInBlock(row,col,value))
        {
           board[row][col] = value;
           new PrintEvent(board);



           if( col < 8 )
              solve(row, col + 1);
           else
              solve(row + 1, 0);

           backtrack++;
         }
      }


      board[row][col] = 0;

      }
   }
 }
like image 572
kompsci Avatar asked Oct 09 '22 09:10

kompsci


1 Answers

Well, you could catch the exception to avoid the stack trace, but that's still not very pretty. What you can do after changing the return type to boolean is:

       if( col < 8 ) {
          if (solve(row, col + 1)) {
              return true;
          }
       } else {
          if (solve(row + 1, 0)) {
              return true;
          }
       }

and then of course, change the throw statements to return true;.

like image 114
Greg Hewgill Avatar answered Oct 12 '22 01:10

Greg Hewgill