Skip to content

Commit c658892

Browse files
committed
is valid sudoku today
1 parent 9de0915 commit c658892

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/is_valid_sudoku.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
from collections import defaultdict
3+
4+
5+
class Solution:
6+
def isValidSudoku(self, board: List[List[str]]) -> bool:
7+
rows = defaultdict(set)
8+
cols = defaultdict(set)
9+
subbox = defaultdict(set) # key is r//3, c//3
10+
11+
for r in range(9):
12+
for c in range(9):
13+
if board[r][c] == ".":
14+
continue
15+
if (
16+
board[r][c] in rows[r]
17+
or board[r][c] in cols[c]
18+
or board[r][c] in subbox[(r // 3, c // 3)]
19+
):
20+
return False
21+
rows[r].add(board[r][c])
22+
cols[c].add(board[r][c])
23+
subbox[(r // 3, c // 3)].add(board[r][c])
24+
return True

tests/test_valid_sudoku.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from is_valid_sudoku import Solution
2+
3+
testcases = [
4+
{
5+
"testcase": [
6+
["5", "3", ".", ".", "7", ".", ".", ".", "."],
7+
["6", ".", ".", "1", "9", "5", ".", ".", "."],
8+
[".", "9", "8", ".", ".", ".", ".", "6", "."],
9+
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
10+
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
11+
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
12+
[".", "6", ".", ".", ".", ".", "2", "8", "."],
13+
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
14+
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
15+
],
16+
"result": True,
17+
}
18+
]
19+
20+
21+
def test_is_valid_sudoku():
22+
for tc in testcases:
23+
board = tc["testcase"]
24+
ans = Solution().isValidSudoku(board)
25+
assert ans == tc["result"]

0 commit comments

Comments
 (0)