Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated following these rules:
1-9
without repetition.1-9
without repetition.3x3
sub-boxes of the grid must contain the digits 1-9
without repetition.The Sudoku board could be partially filled, where empty cells are denoted by the character '.'
.
Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: True
To validate the board, we need to check three main constraints:
We can achieve this by using three sets of hash sets:
We’ll iterate over each cell in the 9x9 board, and for each non-empty cell, we’ll check the constraints. If any constraint fails, we return False
. If no constraints fail, we return True
.
Here’s the implementation:
def isValidSudoku(board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
if board[r][c] == '.':
continue
val = board[r][c]
box_index = (r // 3) * 3 + (c // 3)
if val in rows[r] or val in cols[c] or val in boxes[box_index]:
return False
rows[r].add(val)
cols[c].add(val)
boxes[box_index].add(val)
return True
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?