Search code examples
pythonpython-3.xreturnbacktrackingsudoku

solving a backtracking of sudoku game


I just have learned backtracking yesterday and I'm so confused. In this section

if y == 9:
    if x == 8:
        display(s)
        return 1
    else:
        sudoku(s,x+1,0)

I use return to stop running program but print(sudoku(s,0,0)) still prints None value and not 1. Can anyone figure out why?

s = [[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]]


def display(s):
    for i in s:
        print(*i)


def checkvalid(s,x,y,k):
    for i in range(9):
        if s[x][i] == k or s[i][y] == k:
            return False
    for i in range(x//3*3, x//3*3+3):
        for j in range(y//3*3, y//3*3+3):
            if s[i][j] == k:
                return False
    return True


def sudoku(s,x,y):
    if y == 9:
        if x == 8:
            display(s)
            return 1
        else:
            sudoku(s,x+1,0)
    elif s[x][y] == 0:
        for k in range(1,10):
            if checkvalid(s,x,y, k):
                s[x][y] = k
                sudoku(s,x,y+1)
                s[x][y] = 0
    else:
        sudoku(s,x,y+1)


print(sudoku(s,0,0))

Solution

  • This is because you call sudoku() recursively. Thereby you return 1 to the last caller, which is sudoku() itself from one of the elif/else paths. In those paths you don't return the value back. Instead, you leave the if/elif/else block and exit the function by returning the default value of None.