Function Repository Resource:

SudokuSolve

Source Notebook

Solve Sudoku puzzles

Contributed by: Jon McLoone

ResourceFunction["SudokuSolve"][data]

treats a 9×9 matrix of data as a partially solved Sudoku puzzle and replaces all elements that are not integers from 1 to 9 with the correct elements to fully solve the puzzle.

Details and Options

Sudoku is a popular number puzzle. Its rules are easily stated:
A 9×9 grid is presented, containing some predefined numbers.
The player’s task is to fill in the grid so that every row, every column and the nine 3×3 subgrids contain the digits 1 through 9.

Examples

Basic Examples (1) 

Solve a puzzle:

In[1]:=
ResourceFunction["SudokuSolve"][ {
  { ,  , 8, 1, 7, 6,  , 2,  },
  { , 4,  ,  ,  , 9, 7,  ,  },
  { ,  ,  ,  ,  ,  ,  ,  ,  },
  { , 7, 1, 8,  ,  ,  ,  ,  },
  { ,  ,  ,  ,  ,  , 6, 7, 9},
  { ,  ,  , 5, 9, 7,  , 8, 1},
  { ,  ,  ,  , 2,  ,  ,  ,  },
  { , 5, 9,  ,  ,  ,  , 1,  },
  { , 1, 4, 6, 5,  , 3,  ,  }
 } ]
Out[1]=

Scope (1) 

If a puzzle cannot be solved, a "Contradiction" Failure will be returned:

In[2]:=
{
  {4, , 3, 7, 6, 2, 8, , },
  {, 6, 8, 4, 3, 1, , 7, },
  {, , , , 8, 5, , 3, 6},
  {3, 2, 6, 8, , 9, , 4, },
  {, , 7, , 2, , 9, 6, },
  {, 5, , 1, , 6, 3, 2, },
  {, 4, , 6, 1, , , , },
  {, 3, , 2, , 7, 6, 9, },
  {6, , , , 9, , , , }
 } // ResourceFunction["SudokuSolve"]
Out[2]=

Options (1) 

The option "ShowSteps" shows when it was necessary to guess values rather than use pure logic:

In[3]:=
ResourceFunction["SudokuSolve"][{
  {5, 3, 8, 1, 7, 6,  , 2,  },
  { ,  ,  ,  ,  , 9, 7,  ,  },
  { ,  ,  ,  ,  ,  ,  ,  ,  },
  { , 7, 1, 8,  ,  ,  ,  ,  },
  { ,  ,  ,  ,  ,  , 6, 7, 9},
  { ,  ,  , 5, 9, 7,  , 8, 1},
  { ,  ,  ,  , 2,  ,  ,  ,  },
  { , 5, 9,  ,  ,  ,  , 1,  },
  { , 1, 4, 6, 5,  , 3,  ,  }
 } , "ShowSteps" -> True]
Out[3]=

Publisher

Jon McLoone

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 10 December 2018

License Information