Search⌘ K
AI Features

Sudoku Solver

Explore how to implement a Sudoku solver that fills empty cells in a 2D puzzle array. Understand the use of constraint programming to ensure numbers 1 to 9 do not repeat in rows, columns, or 3x3 sub-boxes, and apply backtracking to try alternative placements if needed. This lesson helps you develop skills to tackle similar constraint-based coding challenges efficiently.

Description

Write a program to solve Sudoku by filling the empty cells. We will be given a 2D array representing a Sudoku puzzle. For a correct solution each of the digits 1-9 must only occur once in each:

  • Row
  • Column
  • Nine 3x3 sub-boxes of the grid

Let us take a look at an example:

To solve the puzzle, we will only fill the empty cells. Empty cells are represented by a ‘.’. The array will be passed by reference, so we will not need to return it after solving the puzzle.

Coding exercise

Python 3.8
def solve_sudoku(board):
# Write code here
pass
Sudoku solver

Solution

While solving Sudoku, we will have to take care of two things. First, we place a number at an empty place. The number must not be present in that row, column, or sub-box. So, we will use constrained programming to keep track of which number we can place in a box and which not. Second, let us assume that we have filled a few empty places but, the choice of numbers was not optimal, ...