-
Notifications
You must be signed in to change notification settings - Fork 0
/
37) Sudoku Solver.py
42 lines (30 loc) · 1.21 KB
/
37) Sudoku Solver.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
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
n = 9
def isValid(row, col, ch):
row, col = int(row), int(col)
for i in range(9):
if board[i][col] == ch:
return False
if board[row][i] == ch:
return False
if board[3*(row//3) + i//3][3*(col//3) + i%3] == ch:
return False
return True
def solve(row, col):
if row == n:
return True
if col == n:
return solve(row+1, 0)
if board[row][col] == ".":
for i in range(1, 10):
if isValid(row, col, str(i)):
board[row][col] = str(i)
if solve(row, col + 1):
return True
else:
board[row][col] = "."
return False
else:
return solve(row, col + 1)
solve(0, 0)