Tech With Tim Logo
Go back

Solving the problem, backtracking.

In part 1 of this Sudoku solver with python tutorial I explain how we are going to go about solving the problem and discuss the algorithm known as backtracking. Backtracking is simply reverting back to the previous step or solution as soon as we determine that our current solution cannot be continued into a complete one. We will use this principle of backtracking to implement the following algorithm.

Algorithm

Starting with an incomplete board:

  1. Find some empty space
  2. Attempt to place the digits 1-9 in that space
  3. Check if that digit is valid in the current spot based on the current board
  4. a. If the digit is valid, recursively attempt to fill the board using steps 1-3. b. If it is not valid, reset the square you just filled and go back to the previous step.
  5. Once the board is full by the definition of this algorithm we have found a solution.

We will finish about half of the algorithm in part 1. In part 2 we will implement the entire algorithm.

Part 1 Code

board = [
    [7,8,0,4,0,0,1,2,0],
    [6,0,0,0,7,5,0,0,9],
    [0,0,0,6,0,1,0,7,8],
    [0,0,7,0,4,0,2,6,0],
    [0,0,1,0,5,0,9,3,0],
    [9,0,4,0,6,0,0,0,5],
    [0,7,0,3,0,0,0,1,2],
    [1,2,0,0,0,7,4,0,0],
    [0,4,9,2,0,6,0,0,7]
]

def print_board(bo):
    for i in range(len(bo)):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - - - - ")

        for j in range(len(bo[0])):
            if j % 3 == 0 and j != 0:
                print(" | ", end="")

            if j == 8:
                print(bo[i][j])
            else:
                print(str(bo[i][j]) + " ", end="")


def find_empty(bo):
    for i in range(len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return (i, j)  # row, col

    return None
Design & Development by Ibezio Logo