Skip to content

Commit

Permalink
Time: 4 ms (60.78%), Space: 17.4 MB (12.03%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
mj3smile committed Dec 14, 2024
1 parent 0d56e6d commit 5077e10
Showing 1 changed file with 45 additions and 12 deletions.
57 changes: 45 additions & 12 deletions 0036-valid-sudoku/0036-valid-sudoku.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,50 @@
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxes = collections.defaultdict(set)
column_cache = dict()
board_cache = dict()

for r in range(len(board)):
for c in range(len(board[1])):
row = r + 1
row_cache = set()

for c in range(len(board[r])):
val = board[r][c]
if val == '.': continue
if (val in rows[r] or
val in cols[c] or
val in boxes[(r // 3, c // 3)]): return False
rows[r].add(val)
cols[c].add(val)
boxes[(r // 3, c // 3)].add(val)
if val == ".":
continue

col = c + 1
board_n = self.getBoard(row, col)
column_cache[col] = column_cache.get(col, set())
board_cache[board_n] = board_cache.get(board_n, set())

return True
if val in row_cache or val in column_cache[col] or val in board_cache[board_n]:
return False

row_cache.add(val)
column_cache[col].add(val)
board_cache[board_n].add(val)

return True

def getBoard(self, row: int, column: int) -> int:
if row in {1, 2, 3}:
if column in {1, 2, 3}:
return 1
elif column in {4, 5, 6}:
return 2
elif column in {7, 8, 9}:
return 3
if row in {4, 5, 6}:
if column in {1, 2, 3}:
return 4
elif column in {4, 5, 6}:
return 5
elif column in {7, 8, 9}:
return 6
if row in {7, 8, 9}:
if column in {1, 2, 3}:
return 7
elif column in {4, 5, 6}:
return 8
elif column in {7, 8, 9}:
return 9

0 comments on commit 5077e10

Please sign in to comment.