動機
照題目做
Problem
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the nine
3 x 3
sub-boxes of the grid must contain the digits1-9
without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board = [[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
Example 2:
Input: board = [[8,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: falseExplanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit or'.'
.
Sol
def h(b,i,j):
hi2 = Counter([int(b[x][j]) for x in range(len(b)) if b[x][j] != "."])
#print(hi2,i,j)
for n in range(1,10):
n = int(n)
#print(hi2.get(n,0))
if hi2.get(n,0) > 1:
return False
return True
def f(b,i,j):
hi = Counter([int(b[i][x]) for x in range(len(b)) if b[i][x] != "."])
for n in range(1,10):
n = int(n)
if hi.get(n,0) > 1:
return False
return True
def g(b,i,j):
hi = set()
for a in range(i,i+3):
for bb in range(j,j+3):
if b[a][bb] != ".":
if b[a][bb] not in hi:
hi.add(b[a][bb])
else:
return True
return False
class Solution:
def isValidSudoku(self, b: List[List[str]]) -> bool:
for i in range(0,9,3):
for j in range(0,9,3):
if g(b,i,j):
return False
return all([h(b,0,j) for j in range(len(b))]) and all([f(b,i,0) for i in range(len(b))])