I come up with this piece of code learning from Youtube. I use this to solve Sudoku by performing Backtracking.
import pandas as pd
import numpy as np
raw = pd.read_csv(r'C:\Users\Administrator\Dropbox\Python_Learning\debaisudoku.csv', header = None)
sudoku = np.nan_to_num(raw)
def possible(x,y,n):
# global sudoku
for i in range(0,9):
if sudoku[i][y] == n:
return False
for i in range(0,9):
if sudoku[x][i] == n:
return False
x0 = (x//3) * 3
y0 = (y//3) * 3
for i in range(0,3):
for j in range(0,3):
if sudoku[x0+i][y0+j] == n:
return False
return True
def solve():
# global sudoku
for x in range(9):
for y in range(9):
if sudoku[x][y] == 0:
for n in range(1,10):
if possible(x,y,n):
sudoku[x][y] = n
if solve(): return True
sudoku[x][y] = 0
return False
print(sudoku)
solve()
Everything is absolutely fine and I understand the code except these lines of code:
if possible(x,y,n):
sudoku[x][y] = n
if solve(): return True
sudoku[x][y] = 0
return False
How Python Runs, Loop, and Remembers the position then continue counting last used number? By the way, if possible, please show me how to perform Backtracking in VBA. I've tried goto with if condition but nothing works.
Thank you so much, I appreciate any answers.