10
10
Only the filled cells need to be validated according to the mentioned rules.
11
11
12
12
Example 1:
13
- Input: board =
13
+ Input: board =
14
14
[["5","3",".",".","7",".",".",".","."]
15
15
,["6",".",".","1","9","5",".",".","."]
16
16
,[".","9","8",".",".",".",".","6","."]
23
23
Output: true
24
24
25
25
Example 2:
26
- Input: board =
26
+ Input: board =
27
27
[["8","3",".",".","7",".",".",".","."]
28
28
,["6",".",".","1","9","5",".",".","."]
29
29
,[".","9","8",".",".",".",".","6","."]
44
44
45
45
from typing import List
46
46
47
+
47
48
def isValidSudoku (board : List [List [str ]]) -> bool :
48
- prevSeen = {
49
- "rows" : { num : {} for num in range (len (board )) },
50
- "columns" : { num : {} for num in range (len (board [0 ])) }
51
- }
52
- buckets = [[{} for _ in range (3 )] for _ in range (3 )]
53
-
54
- for y in range (len (board )):
55
- for x in range (len (board [y ])):
56
- currentNum = board [y ][x ]
57
-
58
- if (currentNum == "." ):
49
+ rowToNums = {}
50
+ columnToNums = {}
51
+ gridToNums = {}
52
+
53
+ for y , _ in enumerate (board ):
54
+ for x , column in enumerate (board [y ]):
55
+ # Skip "." values which aren't necessary to check
56
+ if column == "." :
59
57
continue
60
-
61
- if currentNum in prevSeen ["rows" ][y ]:
62
- return False
63
- if currentNum in prevSeen ["columns" ][x ]:
58
+
59
+ # Set initial tracker keys if not present
60
+ if not y in rowToNums :
61
+ rowToNums [y ] = {}
62
+ if not x in columnToNums :
63
+ columnToNums [x ] = {}
64
+
65
+ yGridBox = y // 3
66
+ xGridBox = x // 3
67
+ gridKey = f"{ yGridBox } { xGridBox } "
68
+ if gridKey not in gridToNums :
69
+ gridToNums [gridKey ] = {}
70
+
71
+ # Perform check for num presence in sub-box grid
72
+ if column in gridToNums [gridKey ]:
64
73
return False
65
-
66
- prevSeen ["rows" ][y ][currentNum ] = True
67
- prevSeen ["columns" ][x ][currentNum ] = True
68
-
69
- bucketY = y // 3
70
- bucketX = x // 3
71
-
72
- if currentNum in buckets [bucketY ][bucketX ]:
74
+
75
+ # Next, perform checks for row/column values
76
+ if column in rowToNums [y ] or column in columnToNums [x ]:
73
77
return False
74
-
75
- buckets [bucketY ][bucketX ][currentNum ] = True
76
-
77
- return True
78
+
79
+ # Set values in trackers for later comparisons
80
+ rowToNums [y ][column ] = True
81
+ columnToNums [x ][column ] = True
82
+ gridToNums [gridKey ][column ] = True
83
+
84
+ return True
0 commit comments