Saturday, November 16, 2024

Excel Simple Sudoku Solver

There are many different ways to solve a Sudoku puzzle with a computer. A previous post explained how to solve Sudoku puzzles with pencil marks and solving techniques (as a human would do), and also using brute force with or without backtracking, something only a computer can do. However, that was all too advanced and created some confusion among readers. In this post, we take a step back and use a very basic solving algorithm, which is probably the simplest way to solve a Sudoku puzzle with a computer. The algorithm applies basic logic to find unique occurrences for each puzzle gap. This will only solve Sudoku puzzles of low and medium difficulty though (maybe some difficult too).


 Sudoku Solving Logic

The easiest way to solve a Sudoku puzzle is to apply simple logic by filling all possible positions where a certain number can potentially be added, and then checking which numbers are unique within a row, column, or block for each of those positions. When unique, the number is solved, and the process repeats again. We will see how this works in more detail later in this post.

But there are many other logic deduction techniques that can be used to solve Sudoku. Using pencil marks allows applying a broad variety of solving techniques such as finding naked singles, hidden singles, naked or hidden pairs, triples, quadruplets, X-wing, Swordfish, XY-wing, and other. We have covered that in this other article: Excel Sudoku Solver.

Ultimately, when logic cannot help solving the puzzle any longer, we may need to make some assumptions or guessing a number’s position. This is something computers can do well and fast. It is often known as brute force and may come along with certain algorithms such as backtracking. That has also been discussed in the previous article.

All about solving and also generating Sudoku puzzles with a computer, and more specifically, with Excel VBA, is explained in detail in this book: Sudoku Excel Macros. The book explains the different VBA functions and objects used to create macros to generate and solve Sudoku in Excel. Besides generating and solving puzzles, the book also discusses how to determine the difficulty of Sudoku puzzles.

 

 

Adding Potential Numbers

Going back to the simple logic algorithm, the solving process consists of two clearly defined steps, and therefore, there are two separate macros; but the second macro is called from within the first one. The first macro adds the potential numbers and has two loops: a first loop through numbers and a second loop through blank cells (puzzle gaps). The code example below shows the first loop.

 
  For num = 1 To 9
      TempRng = SudoRng.Value
      numCount = WorksheetFunction.CountIf(SudoRng, num)
      If numCount < 9 Then        
          'second loop to add numbers to each cell (see later)
      End If
  Next num
 

 

The second loop moves through each blank cell (puzzle gap) and checks whether the number complies with Sudoku rules in that cell. When compliant, the number is added as a potential candidate for that position in another sheet (e.g. Temp).

 
  For Each cell In SudoRng.SpecialCells(xlCellTypeBlanks)
      CellRow = cell.Row
      CellCol = cell.Column
 
      'Check Sudoku conditions to add temporary numbers
      If WorksheetFunction.CountIf(Sudo.Range(boxRng(CellRow, CellCol)), num) = 0 Then
          If WorksheetFunction.CountIf(Sudo.Rows(CellRow), num) = 0 And _
          WorksheetFunction.CountIf(Sudo.Columns(CellCol), num) = 0 Then
              Temp.Cells(CellRow, CellCol).Value = num
          End If
      End If
  Next cell
 
  'Reduce and solve numbers
  Call SolveNumbers(num)
 

 

Let’s see an example to understand how it works. After running the first macro for number 1 only, we get the result below. It shows the puzzle configuration in sheet Temp with all the positions where number 1 could potentially be placed (highlighted in red/orange color).



 
 

Solve Candidate Numbers

After filling all the potential positions for a given number (number 1 in the example above), a second macro (SolveNumbers) checks which numbers are unique within a row, column, or block. This macro is called from within the first one and for each number.

In order to make the process more efficient, it loops by block and only for blocks that are missing that number in the main puzzle. In the example above, it skips the first or third blocks for instance; it just loops through blocks with added numbers (highlighted in red/orange in the picture above). See part of the code for the second macro below.

 
  With Temp
      For GridRow = 2 To 10 Step 3
          For GridCol = 2 To 10 Step 3
              'check if number is not yet solved
              If WorksheetFunction.CountIf(Sudo.Range(boxRng(GridRow, GridCol)), num) = 0 Then
                  'check if number exists in that block
                  If WorksheetFunction.CountIf(.Range(boxRng(GridRow, GridCol)), num) > 0 Then
                      'loop through each cell in that block and find number
                      For Each cell In .Range(boxRng(GridRow, GridCol)).SpecialCells(xlConstants)
                          CellRow = cell.Row
                          CellCol = cell.Column
                       
                          If .Cells(CellRow, CellCol).Value = num Then

                          If WorksheetFunction.CountIf(.Rows(CellRow), num) = 1 Or _
                          WorksheetFunction.CountIf(.Columns(CellCol), num) = 1 Or _
                          WorksheetFunction.CountIf(.Range(boxRng(GridRow, GridCol)), num) = 1 Then
                              Sudo.Cells(CellRow, CellCol).Value = num 
                              .Range(boxRng(GridRow, GridCol)).Replace num, vbNullString
                              .Cells(CellRow, CellCol).Value = num
                              Exit For
                          End If

                          End If
                      Next cell
                  End If
              End If
          Next GridCol
      Next GridRow
  End With

 

The macro loops inside each block in sheet Temp and checks for a unique placement using the worksheet function CountIf. When found, it adds that number to the puzzle and removes the other numbers (if any) in the temporary range in sheet Temp.

Applying this algorithm for number 1 in the puzzle example above returns the following outcome (see below). There are four unique positions for number 1.

 


 

Repeating the Process

The process continues with the next number. See below how the temporary grid looks like for number 2. Note that the macro adds the 2s to the temporary range that already includes the 1s solved in the previous step.



 

Now there are four positions where number 2 is unique and can therefore be solved and added to the puzzle before continuing with the next number.

 



The process continues for all numbers (up to number 9) and then checks whether any changes/additions were made to the initial configuration. That’s done calculating the sum of all numbers before and after the main For loop. If the sum is different, it means some numbers were solved, and then it loops again and repeats the whole process. If the sum is 405 the Sudoku has been solved. However, if the puzzle is not solved and the sum of all numbers has not changed, the program cannot find any position to place the next number and gets stuck. This happens with puzzles of higher difficulty, or when a Sudoku is unsolvable or not “correct” (wrongly designed). For puzzles of higher difficulty, other techniques are needed to solve them – see this other article Excel Sudoku Solver or get the book Sudoku Excel Macros.

 

Download Excel Simple Sudoku Solver 


No comments:

Post a Comment

Popular Posts