Working sudoku code, baffling behaviour

I looked through a number of different versions of how to solve sudoku, and then simplified it to a 3 x 3 grid, and started with a partially completed solution, in order to step through what happens when the ‘solve’ function has to backtrack in pycharm.

The recursive call part of the code I copied from a ‘computerphile’ video on youtube, as it was the bit I couldn’t understand, and needed to work through.

#       part solved,  solution,     original grid
grid = [[1, 2, 4],  #[[1, 2, 4],   [[1, 0, 0],
        [2, 0, 0],  # [2, 3, 1],    [0, 0, 0],
        [0, 0, 3]]  # [4, 1, 3]]    [0, 0, 3]]

print(grid)

def possible(row, col, n):
    for i in range(0, 3):
        if grid[row][i] == n:
            return False
    for i in range(0, 3):
        if grid[i][col] == n:
            return False
    return True


def solve():
    for row in range(3):
        for col in range(3):
            if grid[row][col] == 0: 
                for n in range(1, 5): 
                    if possible(row, col, n):
                        grid[row][col] = n
                        solve()
                        grid[row][col] = 0
                return
    print(grid)
    exit()

solve()

When the loop at line ‘for n in range(1, 5):’ sees the count go past 4, it hits the ‘return’ line nearest the bottom of the page, all okay by me. And then returns to the line above it. Why there? That bit isn’t my code, and I can’t see why it goes there.

After that line it goes back to trying values of n in the previous square. I understand that after ‘return’, it loses the most recent values of ‘col’ and ‘n’ from the stack, reverts to the previous ones, assigns n = 2 and tries that in the previous square. All good stuff, it’s just that baffling return position that gets me.

It’s probably something simple and obvious, can anyone explain?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.