Skip to content

Instantly share code, notes, and snippets.

@btownrippleman
Created April 3, 2020 18:21
Show Gist options
  • Select an option

  • Save btownrippleman/8e326f3fc789dec47840b1c924d8d993 to your computer and use it in GitHub Desktop.

Select an option

Save btownrippleman/8e326f3fc789dec47840b1c924d8d993 to your computer and use it in GitHub Desktop.
import random
class Solution:
global recursion
recursion = 0
def is_full(self,arr):
for i in arr:
for j in i:
if j == '.':
return False
return True
def isValidSudoku(self,matrix,addedValue=None,location=None):
if addedValue:
arr[location[0]][location[1]] = addedValue
for i in range(len(matrix)):
row_arr = []
for j in range(len(matrix)):
if matrix[i][j] in row_arr:
return False
elif matrix[i][j] != ".":
row_arr.append(matrix[i][j])
for col in range(len(matrix)):
col_arr = []
# print("col_arr = "+str(col_arr))
for i in range(len(matrix)):
if matrix[i][col] in col_arr:
return False
elif matrix[i][col] != ".":
col_arr.append(matrix[i][col])
for g in (0,3,6):
for h in (0,3,6):
square_arr = []
for i in range(g,g+3):
for j in range(h,h+3):
if matrix[i][j] in square_arr:
return False
elif matrix[i][j] != ".":
square_arr.append( matrix[i][j])
return True
def solve_sudoku(self,arr):
def get_possibles(arr):
print(np.asarray(arr))
table = {}
for i in range(len(arr)):
for j in range(len(arr)):
if arr[i][j] != ".":
if (i,j) in table:
table.pop(i,j)
else:
table[i,j] = []
for k in range(1,10):
arr[i][j] = k
if self.isValidSudoku(arr):
table[i,j] = table[i,j]+[k]
arr[i][j]="."
return table
def solve(arr):
if self.is_full(arr):
return arr
i,list_ = [(i,v) for i,v in sorted(get_possibles(arr).items(), key=lambda item:len(item[1])) ][0]
i,j = i[0],i[1]
for element in list_:
print(i,j,element, "XXXXXXXXXXXXxx",list_)
arr[i][j] = element
solution = solve(arr)
if solution:
return solution
return solve(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment