def load_puzzle(path):
with open(path) as fin:
contents = fin.read()
lines = contents.split('\n')
sudoku = []
for row in lines:
row_string = row.split()
row_int = [int(n) for n in row_string]
sudoku.append(row_int)
print("Sudoku loaded from", path,"\n")
return sudoku
def display_puzzle(puzzle):
for i in range(len(puzzle)):
if i % 3 == 0:
print("+" + "-------+"*3)
for j in range(len(puzzle[0])):
char = puzzle[i][j]
if char == 0:
char = "."
if j % 3 == 0:
print("| ", end="")
if j == 8:
print(char, "|")
else:
print(str(char) + " ", end = "")
print("+" + "-------+"*3)
def get_next(row, col):
if col < 8:
return row,col+1
elif col == 8 and row < 8:
return row+1,0
elif col == 8 and row == 8:
return None,None
def get_options(puzzle, row, col):
if puzzle[row][col] > 0:
return None
used = []
for i in range(0,9):
if puzzle[row][i] > 0:
used.append(puzzle[row][i])
for i in range(0,9):
if puzzle[i][col] > 0:
used.append(puzzle[i][col])
box_x = row // 3
box_y = col // 3
for i in range(box_x * 3, box_x * 3 + 3):
for j in range(box_y * 3, box_y * 3 + 3):
if puzzle[i][j] > 0:
used.append(puzzle[i][j])
options = []
for i in range(1,10):
if i not in used:
options.append(i)
return options
def copy_puzzle(puzzle):
new_puzzles = []
for i in range(0,len(puzzle)):
new_copy = puzzle[i].copy()
new_puzzles.append(new_copy)
return new_puzzles
def solve(puzzle, row = 0, col = 0):
if puzzle[row][col] != 0:
next_row, next_col = get_next(row,col)
if next_row is None:
return puzzle
else:
return solve(puzzle, next_row, next_col)
options = get_options(puzzle, row, col)
if options == []:
return None
for cur_opt in options:
new_puzzle = copy_puzzle(puzzle)
new_puzzle[row][col] = cur_opt
result = solve(new_puzzle, row, col)
if result is not None:
return result
return None