Skip to content

Commit 4c427c6

Browse files
committed
Change the strategy for backtracking
1 parent a1e6993 commit 4c427c6

File tree

2 files changed

+26
-21
lines changed

2 files changed

+26
-21
lines changed

SudokuSolver/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
def main() -> None:
55

66
sudoku_to_be_solved = import_sudoku()
7-
solve_sudoku(sudoku_to_be_solved, 0, 0)
7+
solve_sudoku(sudoku_to_be_solved)
88

99
if __name__ == '__main__':
1010
main()

SudokuSolver/sudoku_solver.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,46 @@
1+
import numpy as np
12
from move import Move
23
from sudoku import Sudoku
34

45
LEGIT_DIGITS = list(range(1, 10))
56
SUDOKU_DIMENSION = 9
67

7-
def solve_sudoku(sudoku: Sudoku, row: int, column: int) -> bool:
8+
9+
def find_naked_cell(sudoku: Sudoku) -> tuple:
10+
811
'''
9-
Solve a given legal sudoku by appliying a
10-
backtracking strategy.
12+
Finds the first 0 labeled cell in the sudoku
1113
'''
1214

13-
# Return True when the last cell is achieved to avoid further backtracking
14-
15-
if (row == SUDOKU_DIMENSION - 1 and column == SUDOKU_DIMENSION - 1):
16-
print("The solution to the Sudoku proposed is: \n", sudoku.grid)
17-
return True
15+
naked_cells_indexes = np.where(sudoku.grid == 0)
16+
if naked_cells_indexes[0].size > 0:
17+
if naked_cells_indexes[0][0].size > 0 and naked_cells_indexes[1][0].size > 0:
18+
return (naked_cells_indexes[0][0], naked_cells_indexes[1][0])
1819

19-
# If we're in the last column, move to the next row
20+
return naked_cells_indexes
2021

21-
if column == SUDOKU_DIMENSION:
22-
row += 1
23-
column = 0
22+
def solve_sudoku(sudoku: Sudoku,) -> bool:
23+
'''
24+
Solve a given legal sudoku by appliying a
25+
backtracking strategy.
26+
'''
27+
naked_cell = find_naked_cell(sudoku)
2428

25-
if sudoku.grid[row, column] > 0:
26-
return solve_sudoku(sudoku, row, column + 1)
29+
if(not naked_cell[0].size > 0):
30+
print("The solution to the proposed Sudoku is: \n", sudoku.grid)
31+
return True
2732

28-
move = Move(0, row, column)
33+
move = Move(0, naked_cell[0], naked_cell[1])
2934

3035
for digit in LEGIT_DIGITS:
3136
move.number = digit
32-
3337
if sudoku.is_legal_state(move):
3438
sudoku.put_number(move)
35-
36-
if solve_sudoku(sudoku, row, column + 1):
39+
print(sudoku.grid)
40+
if(solve_sudoku(sudoku)):
3741
return True
3842

39-
sudoku.grid[row, column] = 0
40-
43+
move.number = 0
44+
sudoku.put_number(move)
45+
4146
return False

0 commit comments

Comments
 (0)