Sudoku is a popular number puzzle that consists of a 9x9 grid with digits from 1 to 9. The puzzle includes a combination of numbers and some empty spaces, which you need to fill.

When filling in the empty spaces, each row, column, and 3x3 sub-grid should contain all digits from 1 to 9.

A simple Python script can help solve a Sudoku puzzle for you. It can analyze all the empty spaces on the Sudoku board, and find a possible number to fill in each blank space.

How to Create and Display the Sudoku Board

Inside a Python script, you will need to use a list of arrays to store the values of the unsolved Sudoku puzzle.

The code used in this project is available in this GitHub repo under the MIT license.

  1. Inside a new Python script called sudoku.py, store all the values for the 9x9 grid. Each row and column represents the nine numbers across and down the Sudoku puzzle. Add 0s to represent the spaces that need solving:
            board = [
      [5, 3, 0, 0, 7, 0, 0, 0, 0],
      [6, 0, 0, 1, 9, 5, 0, 0, 0],
      [0, 9, 8, 0, 0, 0, 0, 6, 0],
      [8, 0, 0, 0, 6, 0, 0, 0, 3],
      [4, 0, 0, 8, 0, 3, 0, 0, 1],
      [7, 0, 0, 0, 2, 0, 0, 0, 6],
      [0, 6, 0, 0, 0, 0, 2, 8, 0],
      [0, 0, 0, 4, 1, 9, 0, 0, 5],
      [0, 0, 0, 0, 8, 0, 0, 7, 9]
    ]
  2. Inside a new function called print_board, use a for loop to process each row in the grid:
            def print_board(board):
      for row in range(9):
  3. To separate each row into thirds, check if the row is divisible by three, and add a line:
                if row % 3 == 0 and row != 0:
          print("- - - - - - - - - - - - - - ")
  4. Within each row, loop through each column. You can also split columns into thirds by checking if the column is divisible by three:
                for col in range(9):
          if col % 3 == 0 and col != 0:
            print(" | ", end="")
  5. Print the number value stored in the grid. If the column is the last column for that particular row, add a break line, so that the following row appears on a new line:
                  if col == 8:
            print(board[row][col])
          else:
            print(str(board[row][col]) + " ", end="")
  6. Call the function to print the board:
            print_board(board)
        
  7. In a command line, navigate to the folder where you stored your python script, for example:
            cd Desktop
        
  8. Use the python command to run your Sudoku script. View the puzzle printed onto the screen:
            python sudoku.py
        
    cmd with empty sudoku board

How to Identify the Empty Spaces to Solve

You can traverse through the lists to find the spaces that consist of 0s. These determine which spaces needed solving.

  1. In a new function called find_empty(), loop through each row and column on the board:
            def find_empty(board):
      for row in range(9):
        for col in range(9):
  2. If the value of the current cell is 0, return the current position of the empty cell:
                  if board[row][col] == 0:
            return (row, col)
  3. If the script reaches the end of the function, that means the script couldn't find any cells with the value of 0. In this case, do not return anything:
              return None
        
  4. In a new function called solve(), use the find function to find the first empty space on the board:
            def solve(board):
      find = find_empty(board)
  5. The find_empty() function returns the cell position in tuple format, for example, (0, 2). Save these values separately into the row and col variables. Otherwise, return true to signify that there are no empty spaces left to solve:
              if not find:
        return True
      else:
        row, col = find

How to Solve the Puzzle for Each Row, Column, and 3x3 Grid

Now that you can identify the first empty space to solve, you will need to try and find an appropriate number to fill that space and solve the puzzle.

Using recursion, call the solve() function within itself to try every possible combination of values for all the other spaces as well.

  1. Inside the solve() function, after finding the first empty space, loop through each number from 1 to 9. These numbers represent the possible numbers that could fill the unsolved space:
              for num in range(1, 10):
        
  2. Input the board, the possible number, and the position of the empty cell into a new function. The new function will return true if that number is a valid number that can solve that empty space. If it is valid, assign that number to the cell on the board:
                if is_valid(board, num, (row, col)):
          board[row][col] = num
  3. Create the is_valid() function, with matching parameters:
            def is_valid(board, num, pos):
        
  4. Use the function to check if placing the number in that position violates any rules of the Sudoku game. First, check if that number already exists in the row or column of the cell:
              for col in range(9):
        if board[pos[0]][col] == num and pos[1] != col:
          return False

      for row in range(9):
        if board[row][pos[1]] == num and pos[0] != row:
          return False
  5. Get the 3x3 grid that the cell belongs to. You can do this by dividing the cell's position by three:
              box_row = pos[0] // 3
      box_col = pos[1] // 3
  6. For each row and column in that 3x3 grid, check if the number already exists. If it does, return false:
              for row in range(box_row*3, box_row*3 + 3):
        for col in range(box_col*3, box_col*3 + 3):
          if board[row][col] == num and (row, col) != pos:
            return False
  7. If the script reaches the end of the function, that means none of the Sudoku rules failed. Return true:
              return True
        
  8. The is_valid() function only checks if the number placement is valid, but that does not mean it is the correct answer to the overall solution. Within the solve() function, call the solve() function again with the updated board. The solve() function may reach a state where it can no longer use any numbers to fill any spaces. In this case, the entire function returns false, resets that particular cell back to 0, and backtracks. The solve() function only returns true when the script can fill all spaces:
              for num in range(1, 10):
        if is_valid(board, num, (row, col)):
          board[row][col] = num
                
          if solve(board):
            return True
                
          board[row][col] = 0

      return False
  9. To start solving the puzzle, call the solve() function with the original board, at the bottom of the script, after declaring the solve() function:
            solve(board)
        
  10. Print the final result:
            print("Solved:")
    print_board(board)
  11. On the command line, use the python command to re-run the script. View the solved puzzle printed onto the screen:
            python sudoku.py
        
    cmd with solved sudoku board

Creating Games Using Python

Sudoku is just one of the many games you can create and solve using Python. You can use Python to create various other games, such as a word jumble, a text-based adventure game, or a color game, to name just a few.