kying18 / sudoku

Sudoku solver using backtracking
122 stars 74 forks source link

Don't understand everything #5

Closed mdomore closed 3 years ago

mdomore commented 3 years ago

Hi, Thanks for this example and the video.

I try to understand how this work. I understand the logic of backtracking, but i don't understand how in the code you go back in positions. I have try to use breakpoint() and see how it works but i'm confused.

(Pdb) c
guess: 9
row: 0 , col: 8
> /Dev/sandbox/python_sudoku_solver/sudoku.py(77)solve_sudoku()
-> puzzle[row][col] = -1 # reset the guess
(Pdb) c
> /Dev/sandbox/python_sudoku_solver/sudoku.py(76)solve_sudoku()
-> breakpoint()
(Pdb) c
guess: 3
row: 0 , col: 7
> /Dev/sandbox/python_sudoku_solver/sudoku.py(77)solve_sudoku()
-> puzzle[row][col] = -1 # reset the guess

When i reach guess = 9 on row: 0, col: 8, i set it back to -1 (puzzle[row][col] = -1). But how do i go back to row:0 col:7 ?

Please help me understand.

Regards

mdomore commented 3 years ago

After reading, and watching other examples, i understand. It's just recursion. I try to explane what i was missing : When you guess number 9 for column 8, in reality you guess with all the previous guess in a "path", when 9 doesn't work, it tell you that this path is not good to solve the problem, so you backtrack the path and change a guess in a previous column.

I have made some changes to the code to display each step and it's really interesting to watch.

something like :

# now recurse using this puzzle!
# step 4: recursively call our function
print("row: " + str(row) + ",col: " + str(col))
print(np.matrix(puzzle))
input('Press <ENTER> to continue')
if solve_sudoku(puzzle):
    return True