Skip to content

Commit 34c4145

Browse files
committed
daily
1 parent bee1ce4 commit 34c4145

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

my-submissions/h37.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Solution:
2+
def solveSudoku(self, board: List[List[str]]) -> None:
3+
"""
4+
Do not return anything, modify board in-place instead.
5+
"""
6+
board_squares = [[set(), set(), set()] for _ in range(3)]
7+
board_rows = [set() for _ in range(9)]
8+
board_cols = [set() for _ in range(9)]
9+
10+
for r in range(9) :
11+
for c in range(9) :
12+
if board[r][c] == '.' :
13+
continue
14+
board_squares[r // 3][c // 3].add(board[r][c])
15+
board_rows[r].add(board[r][c])
16+
board_cols[c].add(board[r][c])
17+
18+
self._helper(board, board_squares, board_rows, board_cols)
19+
20+
def _helper(self,
21+
board: List[List[str]],
22+
board_squares,
23+
board_rows,
24+
board_cols,
25+
r: int = 0,
26+
c: int = 0) -> bool :
27+
if r >= 9 :
28+
return True
29+
30+
c_next = c + 1
31+
r_next = r
32+
if c_next > 8 :
33+
c_next %= 9
34+
r_next += 1
35+
36+
if board[r][c] != '.' :
37+
return self._helper(board, board_squares, board_rows, board_cols, r_next, c_next)
38+
for candidate in range(1, 10) :
39+
candidate_str = str(candidate)
40+
if (
41+
candidate_str in board_squares[r // 3][c // 3] or
42+
candidate_str in board_rows[r] or
43+
candidate_str in board_cols[c]
44+
) :
45+
continue
46+
47+
board[r][c] = candidate_str
48+
49+
board_squares[r // 3][c // 3].add(candidate_str)
50+
board_rows[r].add(candidate_str)
51+
board_cols[c].add(candidate_str)
52+
53+
54+
if self._helper(board, board_squares, board_rows, board_cols, r_next, c_next) :
55+
return True
56+
57+
board_squares[r // 3][c // 3].remove(candidate_str)
58+
board_rows[r].remove(candidate_str)
59+
board_cols[c].remove(candidate_str)
60+
61+
62+
board[r][c] = '.'
63+
return False

0 commit comments

Comments
 (0)