Created
May 24, 2024 16:14
-
-
Save prodeveloper/629bad36d85f9b0e993e3d0cc9f19c86 to your computer and use it in GitHub Desktop.
Solving sodoku
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solve_soduku(grid): | |
i,j =0,0 | |
while(i<9): | |
while(j<9): | |
if(grid[i][j]==0): | |
if try_fill_missing_recursively(grid,i,j)==False: | |
return False | |
j+=1 | |
j=0 | |
i+=1 | |
return True | |
#Supporting functions for main solver | |
def try_fill_missing_recursively(grid,i,j): | |
for val in range(1,10): | |
if check_valid(grid,i,j,val): | |
grid[i][j]=val | |
if(solve_soduku(grid)): | |
return True | |
else: | |
grid[i][j]=0 | |
return False | |
#Supporting functions for Check Valid | |
def check_valid(grid, i, j, val): | |
if (check_row_unique(grid,j,val)!=True): | |
return False | |
if(check_col_unique(grid,i,val)!=True): | |
return False | |
if(check_three_unique(grid,i,j,val)!=True): | |
return False | |
return True | |
def check_row_unique(grid,j,val): | |
k = 0 | |
while k < 9: | |
if grid[k][j] == val: #keep the col j constant | |
return False | |
k += 1 | |
return True | |
def check_col_unique(grid,i,val): | |
k = 0 | |
while k < 9: | |
if grid[i][k] == val: #keep the row i constant | |
return False | |
k += 1 | |
return True | |
def check_three_unique(grid,i,j,val): | |
start_row = (i//3) * 3 | |
start_col = (j//3) * 3 | |
end_row = start_row + 3 | |
end_col = start_col + 3 | |
while(start_row< end_row): | |
while(start_col< end_col): | |
if(grid[start_row][start_col]==val): | |
return False | |
start_col+=1 | |
start_col= j //3 *3 | |
start_row+=1 | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment