Thursday, February 14, 2013

Simple C Program to solve sudoku game using backtracking

Sudoku can be solved by using backtracking algorithm . As said, "Backtracking is a refinement of the brute force approach, which systematically searches for a solution to a problem among all available options".

Consider you are passing 9x9 matrix to a function called solve().  If the position is filled already no need to worry to about that and fill the empty places . Check every position in the matrix and when you encounter an empty position fill the appropriate value from 1-9  . Before filling the value in the empty position it's corresponding row , column and 3x3 box should not contain the same value . If the row,column and box doesn't contain the value (let's say 1) , 1 will be filled to that position and you can move to next empty position . Remember this can be backtracked and value can be changed (In future if 1 is not suitable backtrack and change it to value from 2-9 which is suitable) .  

Code :(in C)

//call this function to solve sudoku(solve(0,0)) . Here array is global.
void solve( int row, int col)
   {   int num;
       if( row > 8 )
         {   display();
              exit(0);
         }
      if( array[row][col] != 0 )
          next( row, col ) ;
      else
      {
          for( num = 1; num < 10; num++ )
          {
              if( checkRow(row,num) && checkCol(col,num) && checkBox(row,col,num) )
              {
                     array[row][col] = num ;
                      next( row, col ) ;
              }
         }

        array[row][col] = 0 ;
      }
   }

void next( int row, int col )
   {
      if( col < 8 )
         solve( row, col + 1 ) ;
      else
         solve( row + 1, 0 ) ;
   }

int checkRow( int row, int num )
   {
      int col;
      for( col = 0; col < 9; col++ )
         if( array[row][col] == num )
            return 0;
      return 1;
   }

  int  checkCol( int col, int num )
   {  int row;
      for(row = 0; row < 9; row++ )
         if( array[row][col] == num )
            return 0;
      return 1;
   }

 int checkBox( int row, int col, int num )
   {  int r,c;
      row = (row / 3) * 3 ;
      col = (col / 3) * 3 ;
      for(r = 0; r < 3; r++ )
         for(c = 0; c < 3; c++ )
            if( array[row+r][col+c] == num )
                return 0;
      return 1;
   }

Please let me know if you have any questions or doubts . 

No comments: