Last active
August 7, 2020 15:37
-
-
Save prem0862/f459957a4cfd1bf32ff260337f9cd674 to your computer and use it in GitHub Desktop.
This file contains 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
class Solution: | |
def is_row_safe(self, board, num, row): | |
return False if num in board[row] else True | |
def is_col_safe(self, board, num, col): | |
for row in board: | |
if row[col] == num: | |
return False | |
return True | |
def is_box_safe(self, board, num, row, col): | |
row = row - (row % 3) | |
col = col - (col % 3) | |
for r in range(row, row +3): | |
for c in range(col, col +3): | |
if board [r][c] == num: | |
return False | |
return True | |
def safe_position(self, board, row, col, num): | |
row_safe = self.is_row_safe(board, num, row) | |
col_safe = self.is_col_safe(board, num, col) | |
box_safe = self.is_box_safe(board, num, row, col) | |
if (row_safe and col_safe and box_safe): | |
return True | |
return False | |
def sodoku_solver(self, board, lookup_positions): | |
row, col = -1, -1 | |
is_empty = False | |
for i in range(len(lookup_positions)): | |
cordinate = lookup_positions[i] | |
if board[cordinate[0]][cordinate[1]] == ".": | |
row, col = cordinate | |
is_empty = True | |
break | |
if not is_empty: | |
return True | |
# solve soduku | |
for num in range(1, 10): | |
if self.safe_position(board, row, col, num): | |
board[row][col] = num | |
# solve for other position | |
if self.sodoku_solver(board, lookup_positions): | |
return True | |
#backtrack | |
board[row][col] = "." | |
def solveSudoku(self, board): | |
""" | |
:type board: List[List[str]] | |
:rtype: None Do not return anything, modify board in-place instead. | |
""" | |
lookup_positions = [] | |
for row in range(len(board)): | |
for column in range(len(board[0])): | |
if board[row][column] == ".": | |
lookup_positions.append([row, column]) | |
return self.sodoku_solver(board, lookup_positions) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment