|
| 1 | +import numpy as np |
1 | 2 | from move import Move
|
2 | 3 | from sudoku import Sudoku
|
3 | 4 |
|
4 | 5 | LEGIT_DIGITS = list(range(1, 10))
|
5 | 6 | SUDOKU_DIMENSION = 9
|
6 | 7 |
|
7 |
| -def solve_sudoku(sudoku: Sudoku, row: int, column: int) -> bool: |
| 8 | + |
| 9 | +def find_naked_cell(sudoku: Sudoku) -> tuple: |
| 10 | + |
8 | 11 | '''
|
9 |
| - Solve a given legal sudoku by appliying a |
10 |
| - backtracking strategy. |
| 12 | + Finds the first 0 labeled cell in the sudoku |
11 | 13 | '''
|
12 | 14 |
|
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]) |
18 | 19 |
|
19 |
| - # If we're in the last column, move to the next row |
| 20 | + return naked_cells_indexes |
20 | 21 |
|
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) |
24 | 28 |
|
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 |
27 | 32 |
|
28 |
| - move = Move(0, row, column) |
| 33 | + move = Move(0, naked_cell[0], naked_cell[1]) |
29 | 34 |
|
30 | 35 | for digit in LEGIT_DIGITS:
|
31 | 36 | move.number = digit
|
32 |
| - |
33 | 37 | if sudoku.is_legal_state(move):
|
34 | 38 | sudoku.put_number(move)
|
35 |
| - |
36 |
| - if solve_sudoku(sudoku, row, column + 1): |
| 39 | + print(sudoku.grid) |
| 40 | + if(solve_sudoku(sudoku)): |
37 | 41 | return True
|
38 | 42 |
|
39 |
| - sudoku.grid[row, column] = 0 |
40 |
| - |
| 43 | + move.number = 0 |
| 44 | + sudoku.put_number(move) |
| 45 | + |
41 | 46 | return False
|
0 commit comments