-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathsolve-sudoku.py
53 lines (40 loc) · 1.25 KB
/
solve-sudoku.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# SOLVE SUDOKU
# O(1) time and space
def solveSudoku(board):
# Write your code here.
solvePartialSudoku(0, 0, board)
return board
def solvePartialSudoku(row, col, board):
currentRow = row
currentCol = col
if currentCol == len(board[currentRow]):
currentRow += 1
currentCol = 0
if currentRow == len(board):
return True
if board[currentRow][currentCol] == 0:
return tryDigitsAtPosition(currentRow, currentCol, board)
return solvePartialSudoku(currentRow, currentCol + 1, board)
def tryDigitsAtPosition(row, col, board):
for digit in range(1, 10):
if isVAlidAtPosition(digit, row, col, board):
board[row][col] = digit
if solvePartialSudoku(row, col + 1, board):
return True
board[row][col] = 0
return False
def isVAlidAtPosition(value, row, col, board):
rowIsValid = value not in board[row]
columnIsValid = value not in map(lambda r: r[col], board)
if not rowIsValid or not columnIsValid:
return False
subgridRowStart = (row // 3) * 3
subgridColStart = (col // 3) * 3
for rowIdx in range(3):
for colIdx in range(3):
rowToCheck = subgridRowStart + rowIdx
colToCheck = subgridColStart + colIdx
existingValue = board[rowToCheck][colToCheck]
if existingValue == value:
return False
return True