Created
April 18, 2021 12:55
-
-
Save MayankFawkes/8c54a2aac0decc39635cc90a32967515 to your computer and use it in GitHub Desktop.
A simple sudoku solver.
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
| ''' | |
| A simple sudoku solver | |
| ''' | |
| from typing import List | |
| from typing import Tuple | |
| from typing import Union | |
| class sudoku: | |
| def __init__(self, puzzel:List[List[int]]): | |
| self.puzzel = puzzel | |
| self._is_solved:bool = self.solve() | |
| def _completed(self) -> bool: | |
| for r in range(0, 9): | |
| for c in range(0, 9): | |
| if self.puzzel[r][c] == -1: | |
| return False | |
| return True | |
| def _is_valid(self, row:int, column:int, value:int) -> bool: | |
| if value in self.puzzel[row]: | |
| return False | |
| if value in [self.puzzel[row][c] for c in range(0, 9)]: | |
| return False | |
| ro = (row//3) * 3 | |
| co = (column//3) * 3 | |
| for r in range(ro, ro+3): | |
| for c in range(co, co+3): | |
| if self.puzzel[r][c] == value: | |
| return False | |
| return True | |
| def _find_next(self) -> Union[Tuple[int, int], Tuple[None, None]]: | |
| for r in range(0, 9): | |
| for c in range(0, 9): | |
| if self.puzzel[r][c] == -1: | |
| return r,c | |
| return None, None | |
| def solve(self) -> bool: | |
| if self._completed(): | |
| return True | |
| r, c = self._find_next() | |
| for value in range(1,10): | |
| if self._is_valid(r, c, value): | |
| self.puzzel[r][c] = value | |
| return self.solve() | |
| return False | |
| @property | |
| def is_solved(self) -> bool: | |
| return self._is_solved | |
| @property | |
| def solution(self) -> List[List[int]]: | |
| return self.puzzel | |
| if __name__ == '__main__': | |
| puzzel =[[5,1,7,6,-1,-1,-1,3,4], | |
| [2,8,9,-1,-1,4,-1,-1,-1], | |
| [3,4,6,2,-1,5,-1,9,-1], | |
| [6,-1,2,-1,-1,-1,-1,1,-1], | |
| [-1,3,8,-1,-1,6,-1,4,7], | |
| [-1,-1,-1,-1,-1,-1,-1,-1,-1], | |
| [-1,9,-1,-1,-1,-1,-1,7,8], | |
| [7,-1,3,4,-1,-1,5,6,-1], | |
| [-1,-1,-1,-1,-1,-1,-1,-1,-1] | |
| ] | |
| d = sudoku(puzzel) | |
| if d.is_solved: | |
| print(d.solution) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment